Coverage Report

Created: 2024-07-22 04:39

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.91.0 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - See links below.
6
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7
// - Read top of imgui.cpp for more details, links and comments.
8
9
// Resources:
10
// - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md)
11
// - Homepage ................... https://github.com/ocornut/imgui
12
// - Releases & changelog ....... https://github.com/ocornut/imgui/releases
13
// - Gallery .................... https://github.com/ocornut/imgui/issues/7503 (please post your screenshots/video there!)
14
// - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there)
15
//   - Getting Started            https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code)
16
//   - Third-party Extensions     https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more)
17
//   - Bindings/Backends          https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines)
18
//   - Glossary                   https://github.com/ocornut/imgui/wiki/Glossary
19
//   - Debug Tools                https://github.com/ocornut/imgui/wiki/Debug-Tools
20
//   - Software using Dear ImGui  https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui
21
// - Issues & support ........... https://github.com/ocornut/imgui/issues
22
// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps)
23
24
// For first-time users having issues compiling/linking/running/loading fonts:
25
// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
26
// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
27
28
// Copyright (c) 2014-2024 Omar Cornut
29
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
30
// See LICENSE.txt for copyright and licensing details (standard MIT License).
31
// This library is free but needs your support to sustain development and maintenance.
32
// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
33
// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Funding
34
// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
35
36
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
37
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
38
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
39
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
40
// to a better solution or official support for them.
41
42
/*
43
44
Index of this file:
45
46
DOCUMENTATION
47
48
- MISSION STATEMENT
49
- CONTROLS GUIDE
50
- PROGRAMMER GUIDE
51
  - READ FIRST
52
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
53
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
54
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
55
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
56
- API BREAKING CHANGES (read me when you update!)
57
- FREQUENTLY ASKED QUESTIONS (FAQ)
58
  - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
59
60
CODE
61
(search for "[SECTION]" in the code to find them)
62
63
// [SECTION] INCLUDES
64
// [SECTION] FORWARD DECLARATIONS
65
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
66
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
67
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
68
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
69
// [SECTION] MISC HELPERS/UTILITIES (File functions)
70
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
71
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
72
// [SECTION] ImGuiStorage
73
// [SECTION] ImGuiTextFilter
74
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
75
// [SECTION] ImGuiListClipper
76
// [SECTION] STYLING
77
// [SECTION] RENDER HELPERS
78
// [SECTION] INITIALIZATION, SHUTDOWN
79
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
80
// [SECTION] ID STACK
81
// [SECTION] INPUTS
82
// [SECTION] ERROR CHECKING
83
// [SECTION] ITEM SUBMISSION
84
// [SECTION] LAYOUT
85
// [SECTION] SCROLLING
86
// [SECTION] TOOLTIPS
87
// [SECTION] POPUPS
88
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
89
// [SECTION] DRAG AND DROP
90
// [SECTION] LOGGING/CAPTURING
91
// [SECTION] SETTINGS
92
// [SECTION] LOCALIZATION
93
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
94
// [SECTION] DOCKING
95
// [SECTION] PLATFORM DEPENDENT HELPERS
96
// [SECTION] METRICS/DEBUGGER WINDOW
97
// [SECTION] DEBUG LOG WINDOW
98
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
99
100
*/
101
102
//-----------------------------------------------------------------------------
103
// DOCUMENTATION
104
//-----------------------------------------------------------------------------
105
106
/*
107
108
 MISSION STATEMENT
109
 =================
110
111
 - Easy to use to create code-driven and data-driven tools.
112
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
113
 - Easy to hack and improve.
114
 - Minimize setup and maintenance.
115
 - Minimize state storage on user side.
116
 - Minimize state synchronization.
117
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
118
 - Efficient runtime and memory consumption.
119
120
 Designed primarily for developers and content-creators, not the typical end-user!
121
 Some of the current weaknesses (which we aim to address in the future) includes:
122
123
 - Doesn't look fancy.
124
 - Limited layout features, intricate layouts are typically crafted in code.
125
126
127
 CONTROLS GUIDE
128
 ==============
129
130
 - MOUSE CONTROLS
131
   - Mouse wheel:                   Scroll vertically.
132
   - SHIFT+Mouse wheel:             Scroll horizontally.
133
   - Click [X]:                     Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
134
   - Click ^, Double-Click title:   Collapse window.
135
   - Drag on corner/border:         Resize window (double-click to auto fit window to its contents).
136
   - Drag on any empty space:       Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
137
   - Left-click outside popup:      Close popup stack (right-click over underlying popup: Partially close popup stack).
138
139
 - TEXT EDITOR
140
   - Hold SHIFT or Drag Mouse:      Select text.
141
   - CTRL+Left/Right:               Word jump.
142
   - CTRL+Shift+Left/Right:         Select words.
143
   - CTRL+A or Double-Click:        Select All.
144
   - CTRL+X, CTRL+C, CTRL+V:        Use OS clipboard.
145
   - CTRL+Z, CTRL+Y:                Undo, Redo.
146
   - ESCAPE:                        Revert text to its original value.
147
   - On OSX, controls are automatically adjusted to match standard OSX text editing 2ts and behaviors.
148
149
 - KEYBOARD CONTROLS
150
   - Basic:
151
     - Tab, SHIFT+Tab               Cycle through text editable fields.
152
     - CTRL+Tab, CTRL+Shift+Tab     Cycle through windows.
153
     - CTRL+Click                   Input text into a Slider or Drag widget.
154
   - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
155
     - Tab, SHIFT+Tab:              Cycle through every items.
156
     - Arrow keys                   Move through items using directional navigation. Tweak value.
157
     - Arrow keys + Alt, Shift      Tweak slower, tweak faster (when using arrow keys).
158
     - Enter                        Activate item (prefer text input when possible).
159
     - Space                        Activate item (prefer tweaking with arrows when possible).
160
     - Escape                       Deactivate item, leave child window, close popup.
161
     - Page Up, Page Down           Previous page, next page.
162
     - Home, End                    Scroll to top, scroll to bottom.
163
     - Alt                          Toggle between scrolling layer and menu layer.
164
     - CTRL+Tab then Ctrl+Arrows    Move window. Hold SHIFT to resize instead of moving.
165
   - Output when ImGuiConfigFlags_NavEnableKeyboard set,
166
     - io.WantCaptureKeyboard flag is set when keyboard is claimed.
167
     - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
168
     - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
169
170
 - GAMEPAD CONTROLS
171
   - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
172
   - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
173
   - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
174
   - Backend support: backend needs to:
175
      - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
176
      - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
177
        Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
178
      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
179
   - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
180
     with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
181
182
 - REMOTE INPUTS SHARING & MOUSE EMULATION
183
   - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
184
   - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
185
     in order to share your PC mouse/keyboard.
186
   - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
187
   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
188
     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
189
     When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
190
     When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
191
     (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
192
     (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
193
     to set a boolean to ignore your other external mouse positions until the external source is moved again.)
194
195
196
 PROGRAMMER GUIDE
197
 ================
198
199
 READ FIRST
200
 ----------
201
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
202
 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
203
   The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
204
   data retention on your side, less state duplication, less state synchronization, fewer bugs.
205
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
206
   Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
207
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
208
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
209
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
210
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
211
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
212
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
213
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
214
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
215
   If you get an assert, read the messages and comments around the assert.
216
 - This codebase aims to be highly optimized:
217
   - A typical idle frame should never call malloc/free.
218
   - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
219
   - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
220
     Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
221
 - This codebase aims to be both highly opinionated and highly flexible:
222
   - This code works because of the things it choose to solve or not solve.
223
   - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
224
     and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
225
     This is to increase compatibility, increase maintainability and facilitate use from other languages.
226
   - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
227
     See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
228
     We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
229
   - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
230
     (so don't use ImVector in your code or at our own risk!).
231
   - Building: We don't use nor mandate a build system for the main library.
232
     This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
233
     This is also because providing a build system for the main library would be of little-value.
234
     The build problems are almost never coming from the main library but from specific backends.
235
236
237
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
238
 ----------------------------------------------
239
 - Update submodule or copy/overwrite every file.
240
 - About imconfig.h:
241
   - You may modify your copy of imconfig.h, in this case don't overwrite it.
242
   - or you may locally branch to modify imconfig.h and merge/rebase latest.
243
   - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
244
     specify a custom path for your imconfig.h file and instead not have to modify the default one.
245
246
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
247
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
248
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
249
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
250
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
251
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
252
   likely be a comment about it. Please report any issue to the GitHub page!
253
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
254
 - Try to keep your copy of Dear ImGui reasonably up to date!
255
256
257
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
258
 ---------------------------------------------------------------
259
 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
260
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
261
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
262
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
263
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
264
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
265
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
266
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
267
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
268
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
269
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
270
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
271
272
273
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
274
 --------------------------------------
275
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
276
 The sub-folders in examples/ contain examples applications following this structure.
277
278
     // Application init: create a dear imgui context, setup some options, load fonts
279
     ImGui::CreateContext();
280
     ImGuiIO& io = ImGui::GetIO();
281
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
282
     // TODO: Fill optional fields of the io structure later.
283
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
284
285
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
286
     ImGui_ImplWin32_Init(hwnd);
287
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
288
289
     // Application main loop
290
     while (true)
291
     {
292
         // Feed inputs to dear imgui, start new frame
293
         ImGui_ImplDX11_NewFrame();
294
         ImGui_ImplWin32_NewFrame();
295
         ImGui::NewFrame();
296
297
         // Any application code here
298
         ImGui::Text("Hello, world!");
299
300
         // Render dear imgui into screen
301
         ImGui::Render();
302
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
303
         g_pSwapChain->Present(1, 0);
304
     }
305
306
     // Shutdown
307
     ImGui_ImplDX11_Shutdown();
308
     ImGui_ImplWin32_Shutdown();
309
     ImGui::DestroyContext();
310
311
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
312
313
     // Application init: create a dear imgui context, setup some options, load fonts
314
     ImGui::CreateContext();
315
     ImGuiIO& io = ImGui::GetIO();
316
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
317
     // TODO: Fill optional fields of the io structure later.
318
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
319
320
     // Build and load the texture atlas into a texture
321
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
322
     int width, height;
323
     unsigned char* pixels = nullptr;
324
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
325
326
     // At this point you've got the texture data and you need to upload that to your graphic system:
327
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
328
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
329
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
330
     io.Fonts->SetTexID((void*)texture);
331
332
     // Application main loop
333
     while (true)
334
     {
335
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
336
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
337
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
338
        io.DisplaySize.x = 1920.0f;             // set the current display width
339
        io.DisplaySize.y = 1280.0f;             // set the current display height here
340
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
341
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
342
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
343
344
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
345
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
346
        ImGui::NewFrame();
347
348
        // Most of your application code here
349
        ImGui::Text("Hello, world!");
350
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
351
        MyGameRender(); // may use any Dear ImGui functions as well!
352
353
        // Render dear imgui, swap buffers
354
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
355
        ImGui::EndFrame();
356
        ImGui::Render();
357
        ImDrawData* draw_data = ImGui::GetDrawData();
358
        MyImGuiRenderFunction(draw_data);
359
        SwapBuffers();
360
     }
361
362
     // Shutdown
363
     ImGui::DestroyContext();
364
365
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
366
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
367
 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
368
369
370
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
371
 ---------------------------------------------
372
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
373
374
    void MyImGuiRenderFunction(ImDrawData* draw_data)
375
    {
376
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
377
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
378
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
379
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
380
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
381
       ImVec2 clip_off = draw_data->DisplayPos;
382
       for (int n = 0; n < draw_data->CmdListsCount; n++)
383
       {
384
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
385
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
386
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
387
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
388
          {
389
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
390
             if (pcmd->UserCallback)
391
             {
392
                 pcmd->UserCallback(cmd_list, pcmd);
393
             }
394
             else
395
             {
396
                 // Project scissor/clipping rectangles into framebuffer space
397
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
398
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
399
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
400
                     continue;
401
402
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
403
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
404
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
405
                 // - Clipping coordinates are provided in imgui coordinates space:
406
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
407
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
408
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
409
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
410
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
411
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
412
413
                 // The texture for the draw call is specified by pcmd->GetTexID().
414
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
415
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
416
417
                 // Render 'pcmd->ElemCount/3' indexed triangles.
418
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
419
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
420
             }
421
          }
422
       }
423
    }
424
425
426
 API BREAKING CHANGES
427
 ====================
428
429
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
430
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
431
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
432
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
433
434
(Docking/Viewport Branch)
435
 - 2024/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
436
                          - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
437
                            you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
438
                          - likewise io.MousePos and GetMousePos() will use OS coordinates.
439
                            If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
440
441
 - 2024/07/02 (1.91.0) - commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456)
442
                       - commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456)
443
                            - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc.
444
 - 2024/07/02 (1.91.0) - IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness.
445
                            - old: io.SetPlatformImeDataFn(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
446
                            - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
447
 - 2024/06/21 (1.90.9) - BeginChild: added ImGuiChildFlags_NavFlattened as a replacement for the window flag ImGuiWindowFlags_NavFlattened: the feature only ever made sense for BeginChild() anyhow.
448
                            - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened);
449
                            - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0);
450
 - 2024/06/21 (1.90.9) - io: ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data, newly added ClearInputMouse() does.
451
 - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire.
452
 - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected.
453
 - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages).
454
 - 2024/06/06 (1.90.8) - reordered ImGuiInputTextFlags values. This should not be breaking unless you are using generated headers that have values not matching the main library.
455
 - 2024/06/06 (1.90.8) - removed 'ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft', was mostly unused and misleading.
456
 - 2024/05/27 (1.90.7) - commented out obsolete symbols marked obsolete in 1.88 (May 2022):
457
                            - old: CaptureKeyboardFromApp(bool)
458
                            - new: SetNextFrameWantCaptureKeyboard(bool)
459
                            - old: CaptureMouseFromApp(bool)
460
                            - new: SetNextFrameWantCaptureMouse(bool)
461
 - 2024/05/22 (1.90.7) - inputs (internals): renamed ImGuiKeyOwner_None to ImGuiKeyOwner_NoOwner, to make use more explicit and reduce confusion with the default it is a non-zero value and cannot be the default value (never made public, but disclosing as I expect a few users caught on owner-aware inputs).
462
                       - inputs (internals): renamed ImGuiInputFlags_RouteGlobalLow -> ImGuiInputFlags_RouteGlobal, ImGuiInputFlags_RouteGlobal -> ImGuiInputFlags_RouteGlobalOverFocused, ImGuiInputFlags_RouteGlobalHigh -> ImGuiInputFlags_RouteGlobalHighest.
463
                       - inputs (internals): Shortcut(), SetShortcutRouting(): swapped last two parameters order in function signatures:
464
                            - old: Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id = 0, ImGuiInputFlags flags = 0);
465
                            - new: Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0, ImGuiID owner_id = 0);
466
                       - inputs (internals): owner-aware versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(): swapped last two parameters order in function signatures.
467
                            - old: IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0);
468
                            - new: IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0);
469
                            - old: IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags = 0);
470
                            - new: IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0);
471
                         for various reasons those changes makes sense. They are being made because making some of those API public.
472
                         only past users of imgui_internal.h with the extra parameters will be affected. Added asserts for valid flags in various functions to detect _some_ misuses, BUT NOT ALL.
473
 - 2024/05/21 (1.90.7) - docking: changed signature of DockSpaceOverViewport() to add explicit dockspace id if desired. pass 0 to use old behavior. (#7611)
474
                           - old: DockSpaceOverViewport(const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
475
                           - new: DockSpaceOverViewport(ImGuiID dockspace_id = 0, const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
476
 - 2024/05/16 (1.90.7) - inputs: on macOS X, Cmd and Ctrl keys are now automatically swapped by io.AddKeyEvent() as this naturally align with how macOS X uses those keys.
477
                           - it shouldn't really affect you unless you had custom shortcut swapping in place for macOS X apps.
478
                           - removed ImGuiMod_Shortcut which was previously dynamically remapping to Ctrl or Cmd/Super. It is now unnecessary to specific cross-platform idiomatic shortcuts. (#2343, #4084, #5923, #456)
479
 - 2024/05/14 (1.90.7) - backends: SDL_Renderer2 and SDL_Renderer3 backend now take a SDL_Renderer* in their RenderDrawData() functions.
480
 - 2024/04/18 (1.90.6) - TreeNode: Fixed a layout inconsistency when using an empty/hidden label followed by a SameLine() call. (#7505, #282)
481
                           - old: TreeNode("##Hidden"); SameLine(); Text("Hello");     // <-- This was actually incorrect! BUT appeared to look ok with the default style where ItemSpacing.x == FramePadding.x * 2 (it didn't look aligned otherwise).
482
                           - new: TreeNode("##Hidden"); SameLine(0, 0); Text("Hello"); // <-- This is correct for all styles values.
483
                         with the fix, IF you were successfully using TreeNode("")+SameLine(); you will now have extra spacing between your TreeNode and the following item.
484
                         You'll need to change the SameLine() call to SameLine(0,0) to remove this extraneous spacing. This seemed like the more sensible fix that's not making things less consistent.
485
                         (Note: when using this idiom you are likely to also use ImGuiTreeNodeFlags_SpanAvailWidth).
486
 - 2024/03/18 (1.90.5) - merged the radius_x/radius_y parameters in ImDrawList::AddEllipse(), AddEllipseFilled() and PathEllipticalArcTo() into a single ImVec2 parameter. Exceptionally, because those functions were added in 1.90, we are not adding inline redirection functions. The transition is easy and should affect few users. (#2743, #7417)
487
 - 2024/03/08 (1.90.5) - inputs: more formally obsoleted GetKeyIndex() when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is set. It has been unnecessary and a no-op since 1.87 (it returns the same value as passed when used with a 1.87+ backend using io.AddKeyEvent() function). (#4921)
488
                           - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
489
 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
490
 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
491
 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
492
 - 2023/11/05 (1.90.1) - imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls.
493
 - 2023/11/05 (1.90.1) - internals,columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80.
494
 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
495
 - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete).
496
                         those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.
497
 - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work.
498
                           - old: BeginChild("Name", size, true)
499
                           - new: BeginChild("Name", size, ImGuiChildFlags_Border)
500
                           - old: BeginChild("Name", size, false)
501
                           - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
502
 - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow.
503
                           - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
504
                           - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
505
 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
506
 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
507
 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
508
                           - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
509
                           - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
510
                           - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
511
                           - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
512
 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
513
                           - GetWindowContentRegionWidth()  -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
514
                           - ImDrawCornerFlags_XXX          -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
515
                       - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
516
 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
517
 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
518
 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
519
 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
520
 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
521
 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
522
 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
523
 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
524
 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
525
                           - ListBoxHeader()  -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
526
                           - ListBoxFooter()  -> use EndListBox()
527
 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
528
 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
529
 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
530
                           - ImGuiSliderFlags_ClampOnInput        -> use ImGuiSliderFlags_AlwaysClamp
531
                           - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
532
                           - ImDrawList::AddBezierCurve()         -> use ImDrawList::AddBezierCubic()
533
                           - ImDrawList::PathBezierCurveTo()      -> use ImDrawList::PathBezierCubicCurveTo()
534
 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
535
 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
536
 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
537
                         Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
538
                         it has been frequently requested by people to use our own. We had an opt-in define which was
539
                         previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
540
                           - OK:     #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
541
                           - Error:  #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
542
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
543
 - 2022/10/26 (1.89)   - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
544
 - 2022/10/12 (1.89)   - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
545
 - 2022/09/26 (1.89)   - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
546
                           - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
547
                           - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
548
                           - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
549
                           - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
550
                         the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
551
                         the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
552
                         exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
553
 - 2022/09/20 (1.89)   - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
554
                         this will require uses of legacy backend-dependent indices to be casted, e.g.
555
                            - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
556
                            - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
557
                            - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
558
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
559
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
560
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
561
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
562
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
563
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
564
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
565
                         - previously this would make the window content size ~200x200:
566
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
567
                         - instead, please submit an item:
568
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
569
                         - alternative:
570
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
571
                         - content size is now only extended when submitting an item!
572
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
573
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
574
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
575
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
576
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
577
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
578
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
579
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
580
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
581
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
582
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
583
                        - Official backends from 1.87+                  -> no issue.
584
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
585
                        - Custom backends not writing to io.NavInputs[] -> no issue.
586
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
587
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
588
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
589
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
590
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
591
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
592
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
593
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
594
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
595
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
596
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
597
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
598
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
599
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
600
                       read https://github.com/ocornut/imgui/issues/4921 for details.
601
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
602
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
603
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
604
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
605
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
606
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
607
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
608
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
609
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
610
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
611
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
612
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
613
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
614
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
615
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
616
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
617
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
618
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
619
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
620
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
621
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
622
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
623
                        - if you are using official backends from the source tree: you have nothing to do.
624
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
625
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
626
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
627
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
628
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
629
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
630
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
631
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
632
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
633
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
634
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
635
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
636
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
637
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
638
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
639
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
640
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
641
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
642
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
643
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
644
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
645
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
646
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
647
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
648
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
649
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
650
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
651
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
652
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
653
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
654
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
655
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
656
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
657
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
658
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
659
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
660
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
661
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
662
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
663
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
664
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
665
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
666
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
667
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
668
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
669
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
670
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
671
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
672
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
673
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
674
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
675
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
676
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
677
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
678
                       - if you omitted the 'power' parameter (likely!), you are not affected.
679
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
680
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
681
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
682
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
683
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
684
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
685
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
686
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
687
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
688
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
689
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
690
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
691
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
692
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
693
                       - ShowTestWindow()                    -> use ShowDemoWindow()
694
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
695
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
696
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
697
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
698
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
699
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
700
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
701
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
702
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
703
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
704
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
705
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
706
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
707
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
708
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
709
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
710
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
711
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
712
                       - ImFont::Glyph                       -> use ImFontGlyph
713
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
714
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
715
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
716
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
717
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
718
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
719
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
720
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
721
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
722
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
723
                       Please reach out if you are affected.
724
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
725
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
726
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
727
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
728
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
729
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
730
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
731
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
732
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
733
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
734
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
735
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
736
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
737
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
738
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
739
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
740
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
741
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
742
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
743
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
744
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
745
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
746
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
747
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
748
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
749
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
750
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
751
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
752
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
753
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
754
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
755
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
756
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
757
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
758
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
759
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
760
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
761
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
762
                       consistent with other functions. Kept redirection functions (will obsolete).
763
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
764
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
765
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
766
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
767
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
768
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
769
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
770
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
771
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
772
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
773
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
774
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
775
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
776
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
777
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
778
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
779
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
780
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
781
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
782
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
783
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
784
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
785
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
786
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
787
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
788
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
789
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
790
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
791
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
792
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
793
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
794
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
795
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
796
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
797
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
798
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
799
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
800
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
801
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
802
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
803
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
804
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
805
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
806
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
807
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
808
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
809
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
810
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
811
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
812
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
813
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
814
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
815
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
816
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
817
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
818
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
819
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
820
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
821
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
822
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
823
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
824
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
825
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
826
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
827
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
828
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
829
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
830
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
831
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
832
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
833
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
834
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
835
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
836
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
837
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
838
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
839
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
840
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
841
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
842
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
843
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
844
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
845
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
846
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
847
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
848
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
849
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
850
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
851
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
852
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
853
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
854
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
855
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
856
                     - the signature of the io.RenderDrawListsFn handler has changed!
857
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
858
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
859
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
860
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
861
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
862
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
863
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
864
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
865
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
866
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
867
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
868
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
869
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
870
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
871
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
872
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
873
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
874
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
875
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
876
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
877
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
878
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
879
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
880
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
881
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
882
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
883
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
884
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
885
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
886
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
887
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
888
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
889
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
890
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
891
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
892
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
893
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
894
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
895
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
896
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
897
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
898
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
899
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
900
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
901
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
902
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
903
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
904
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
905
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
906
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
907
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
908
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
909
910
911
 FREQUENTLY ASKED QUESTIONS (FAQ)
912
 ================================
913
914
 Read all answers online:
915
   https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
916
 Read all answers locally (with a text editor or ideally a Markdown viewer):
917
   docs/FAQ.md
918
 Some answers are copied down here to facilitate searching in code.
919
920
 Q&A: Basics
921
 ===========
922
923
 Q: Where is the documentation?
924
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
925
    - Run the examples/ applications and explore them.
926
    - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
927
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
928
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
929
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
930
    - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
931
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
932
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
933
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
934
    - Your programming IDE is your friend, find the type or function declaration to find comments
935
      associated with it.
936
937
 Q: What is this library called?
938
 Q: Which version should I get?
939
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
940
 >> See https://www.dearimgui.com/faq for details.
941
942
 Q&A: Integration
943
 ================
944
945
 Q: How to get started?
946
 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
947
948
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
949
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
950
 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
951
952
 Q. How can I enable keyboard or gamepad controls?
953
 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
954
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
955
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
956
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
957
 >> See https://www.dearimgui.com/faq
958
959
 Q&A: Usage
960
 ----------
961
962
 Q: About the ID Stack system..
963
   - Why is my widget not reacting when I click on it?
964
   - How can I have widgets with an empty label?
965
   - How can I have multiple widgets with the same label?
966
   - How can I have multiple windows with the same label?
967
 Q: How can I display an image? What is ImTextureID, how does it work?
968
 Q: How can I use my own math types instead of ImVec2?
969
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
970
 Q: How can I display custom shapes? (using low-level ImDrawList API)
971
 >> See https://www.dearimgui.com/faq
972
973
 Q&A: Fonts, Text
974
 ================
975
976
 Q: How should I handle DPI in my application?
977
 Q: How can I load a different font than the default?
978
 Q: How can I easily use icons in my application?
979
 Q: How can I load multiple fonts?
980
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
981
 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
982
983
 Q&A: Concerns
984
 =============
985
986
 Q: Who uses Dear ImGui?
987
 Q: Can you create elaborate/serious tools with Dear ImGui?
988
 Q: Can you reskin the look of Dear ImGui?
989
 Q: Why using C++ (as opposed to C)?
990
 >> See https://www.dearimgui.com/faq
991
992
 Q&A: Community
993
 ==============
994
995
 Q: How can I help?
996
 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
997
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
998
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
999
      >>> See https://github.com/ocornut/imgui/wiki/Funding
1000
    - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
1001
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
1002
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
1003
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
1004
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
1005
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
1006
1007
*/
1008
1009
//-------------------------------------------------------------------------
1010
// [SECTION] INCLUDES
1011
//-------------------------------------------------------------------------
1012
1013
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
1014
#define _CRT_SECURE_NO_WARNINGS
1015
#endif
1016
1017
#ifndef IMGUI_DEFINE_MATH_OPERATORS
1018
#define IMGUI_DEFINE_MATH_OPERATORS
1019
#endif
1020
1021
#include "imgui.h"
1022
#ifndef IMGUI_DISABLE
1023
#include "imgui_internal.h"
1024
1025
// System includes
1026
#include <stdio.h>      // vsnprintf, sscanf, printf
1027
#include <stdint.h>     // intptr_t
1028
1029
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
1030
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
1031
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1032
#endif
1033
1034
// [Windows] OS specific includes (optional)
1035
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1036
#define IMGUI_DISABLE_WIN32_FUNCTIONS
1037
#endif
1038
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1039
#ifndef WIN32_LEAN_AND_MEAN
1040
#define WIN32_LEAN_AND_MEAN
1041
#endif
1042
#ifndef NOMINMAX
1043
#define NOMINMAX
1044
#endif
1045
#ifndef __MINGW32__
1046
#include <Windows.h>        // _wfopen, OpenClipboard
1047
#else
1048
#include <windows.h>
1049
#endif
1050
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP || WINAPI_FAMILY == WINAPI_FAMILY_GAMES)
1051
// The UWP and GDK Win32 API subsets don't support clipboard nor IME functions
1052
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1053
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1054
#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
1055
#endif
1056
#endif
1057
1058
// [Apple] OS specific includes
1059
#if defined(__APPLE__)
1060
#include <TargetConditionals.h>
1061
#endif
1062
1063
// Visual Studio warnings
1064
#ifdef _MSC_VER
1065
#pragma warning (disable: 4127)             // condition expression is constant
1066
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1067
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
1068
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
1069
#endif
1070
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
1071
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1072
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1073
#endif
1074
1075
// Clang/GCC warnings with -Weverything
1076
#if defined(__clang__)
1077
#if __has_warning("-Wunknown-warning-option")
1078
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
1079
#endif
1080
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
1081
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
1082
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
1083
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
1084
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
1085
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
1086
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
1087
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
1088
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
1089
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
1090
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
1091
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
1092
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage"            // warning: 'xxx' is an unsafe pointer used for buffer access
1093
#elif defined(__GNUC__)
1094
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1095
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
1096
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
1097
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
1098
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1099
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
1100
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1101
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
1102
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1103
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
1104
#endif
1105
1106
// Debug options
1107
167k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
1108
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
1109
1110
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1111
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
1112
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
1113
1114
static const float NAV_ACTIVATE_HIGHLIGHT_TIMER             = 0.10f;    // Time to highlight an item activated by a shortcut.
1115
1116
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1117
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1118
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
1119
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1120
1121
// Tooltip offset
1122
static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10);            // Multiplied by g.Style.MouseCursorScale
1123
1124
// Docking
1125
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1126
1127
//-------------------------------------------------------------------------
1128
// [SECTION] FORWARD DECLARATIONS
1129
//-------------------------------------------------------------------------
1130
1131
static void             SetCurrentWindow(ImGuiWindow* window);
1132
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1133
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1134
1135
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1136
1137
// Settings
1138
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1139
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1140
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1141
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1142
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1143
1144
// Platform Dependents default implementation for IO functions
1145
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1146
static void             SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1147
static void             PlatformSetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1148
static bool             PlatformOpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path);
1149
1150
namespace ImGui
1151
{
1152
// Item
1153
static void             ItemHandleShortcut(ImGuiID id);
1154
1155
// Navigation
1156
static void             NavUpdate();
1157
static void             NavUpdateWindowing();
1158
static void             NavUpdateWindowingOverlay();
1159
static void             NavUpdateCancelRequest();
1160
static void             NavUpdateCreateMoveRequest();
1161
static void             NavUpdateCreateTabbingRequest();
1162
static float            NavUpdatePageUpPageDown();
1163
static inline void      NavUpdateAnyRequestFlag();
1164
static void             NavUpdateCreateWrappingRequest();
1165
static void             NavEndFrame();
1166
static bool             NavScoreItem(ImGuiNavItemData* result);
1167
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1168
static void             NavProcessItem();
1169
static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1170
static ImVec2           NavCalcPreferredRefPos();
1171
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1172
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1173
static void             NavRestoreLayer(ImGuiNavLayer layer);
1174
static int              FindWindowFocusIndex(ImGuiWindow* window);
1175
1176
// Error Checking and Debug Tools
1177
static void             ErrorCheckNewFrameSanityChecks();
1178
static void             ErrorCheckEndFrameSanityChecks();
1179
static void             UpdateDebugToolItemPicker();
1180
static void             UpdateDebugToolStackQueries();
1181
static void             UpdateDebugToolFlashStyleColor();
1182
1183
// Inputs
1184
static void             UpdateKeyboardInputs();
1185
static void             UpdateMouseInputs();
1186
static void             UpdateMouseWheel();
1187
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1188
1189
// Misc
1190
static void             UpdateSettings();
1191
static int              UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1192
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1193
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1194
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1195
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1196
static void             RenderDimmedBackgrounds();
1197
static void             SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect);
1198
1199
// Viewports
1200
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1201
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1202
static void             DestroyViewport(ImGuiViewportP* viewport);
1203
static void             UpdateViewportsNewFrame();
1204
static void             UpdateViewportsEndFrame();
1205
static void             WindowSelectViewport(ImGuiWindow* window);
1206
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1207
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1208
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1209
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1210
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1211
static int              FindPlatformMonitorForRect(const ImRect& r);
1212
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1213
1214
}
1215
1216
//-----------------------------------------------------------------------------
1217
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1218
//-----------------------------------------------------------------------------
1219
1220
// DLL users:
1221
// - Heaps and globals are not shared across DLL boundaries!
1222
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1223
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1224
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1225
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1226
1227
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1228
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1229
//   Change to a different context by calling ImGui::SetCurrentContext().
1230
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1231
//   If you want thread-safety to allow N threads to access N different contexts:
1232
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1233
//         struct ImGuiContext;
1234
//         extern thread_local ImGuiContext* MyImGuiTLS;
1235
//         #define GImGui MyImGuiTLS
1236
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1237
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1238
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1239
// - DLL users: read comments above.
1240
#ifndef GImGui
1241
ImGuiContext*   GImGui = NULL;
1242
#endif
1243
1244
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1245
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1246
// - DLL users: read comments above.
1247
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1248
1.22k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1249
1.17k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1250
#else
1251
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1252
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1253
#endif
1254
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1255
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1256
static void*                GImAllocatorUserData = NULL;
1257
1258
//-----------------------------------------------------------------------------
1259
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1260
//-----------------------------------------------------------------------------
1261
1262
ImGuiStyle::ImGuiStyle()
1263
1
{
1264
1
    Alpha                       = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1265
1
    DisabledAlpha               = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1266
1
    WindowPadding               = ImVec2(8,8);      // Padding within a window
1267
1
    WindowRounding              = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1268
1
    WindowBorderSize            = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1269
1
    WindowMinSize               = ImVec2(32,32);    // Minimum window size
1270
1
    WindowTitleAlign            = ImVec2(0.0f,0.5f);// Alignment for title bar text
1271
1
    WindowMenuButtonPosition    = ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1272
1
    ChildRounding               = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1273
1
    ChildBorderSize             = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1274
1
    PopupRounding               = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1275
1
    PopupBorderSize             = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1276
1
    FramePadding                = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1277
1
    FrameRounding               = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1278
1
    FrameBorderSize             = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1279
1
    ItemSpacing                 = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1280
1
    ItemInnerSpacing            = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1281
1
    CellPadding                 = ImVec2(4,2);      // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows.
1282
1
    TouchExtraPadding           = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1283
1
    IndentSpacing               = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1284
1
    ColumnsMinSpacing           = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1285
1
    ScrollbarSize               = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1286
1
    ScrollbarRounding           = 9.0f;             // Radius of grab corners rounding for scrollbar
1287
1
    GrabMinSize                 = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1288
1
    GrabRounding                = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1289
1
    LogSliderDeadzone           = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1290
1
    TabRounding                 = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1291
1
    TabBorderSize               = 0.0f;             // Thickness of border around tabs.
1292
1
    TabMinWidthForCloseButton   = 0.0f;             // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1293
1
    TabBarBorderSize            = 1.0f;             // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1294
1
    TableAngledHeadersAngle     = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1295
1
    TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell
1296
1
    ColorButtonPosition         = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1297
1
    ButtonTextAlign             = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1298
1
    SelectableTextAlign         = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1299
1
    SeparatorTextBorderSize     = 3.0f;             // Thickkness of border in SeparatorText()
1300
1
    SeparatorTextAlign          = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1301
1
    SeparatorTextPadding        = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1302
1
    DisplayWindowPadding        = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1303
1
    DisplaySafeAreaPadding      = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1304
1
    DockingSeparatorSize        = 2.0f;             // Thickness of resizing border between docked windows
1305
1
    MouseCursorScale            = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1306
1
    AntiAliasedLines            = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1307
1
    AntiAliasedLinesUseTex      = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1308
1
    AntiAliasedFill             = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1309
1
    CurveTessellationTol        = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1310
1
    CircleTessellationMaxError  = 0.30f;            // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1311
1312
    // Behaviors
1313
1
    HoverStationaryDelay        = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1314
1
    HoverDelayShort             = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1315
1
    HoverDelayNormal            = 0.40f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1316
1
    HoverFlagsForTooltipMouse   = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled;    // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1317
1
    HoverFlagsForTooltipNav     = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled;  // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1318
1319
    // Default theme
1320
1
    ImGui::StyleColorsDark(this);
1321
1
}
1322
1323
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1324
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1325
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1326
0
{
1327
0
    WindowPadding = ImTrunc(WindowPadding * scale_factor);
1328
0
    WindowRounding = ImTrunc(WindowRounding * scale_factor);
1329
0
    WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1330
0
    ChildRounding = ImTrunc(ChildRounding * scale_factor);
1331
0
    PopupRounding = ImTrunc(PopupRounding * scale_factor);
1332
0
    FramePadding = ImTrunc(FramePadding * scale_factor);
1333
0
    FrameRounding = ImTrunc(FrameRounding * scale_factor);
1334
0
    ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1335
0
    ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1336
0
    CellPadding = ImTrunc(CellPadding * scale_factor);
1337
0
    TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1338
0
    IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1339
0
    ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1340
0
    ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1341
0
    ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1342
0
    GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1343
0
    GrabRounding = ImTrunc(GrabRounding * scale_factor);
1344
0
    LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1345
0
    TabRounding = ImTrunc(TabRounding * scale_factor);
1346
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1347
0
    SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1348
0
    DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
1349
0
    DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1350
0
    DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1351
0
    MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1352
0
}
1353
1354
ImGuiIO::ImGuiIO()
1355
1
{
1356
    // Most fields are initialized with zero
1357
1
    memset(this, 0, sizeof(*this));
1358
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1359
1360
    // Settings
1361
1
    ConfigFlags = ImGuiConfigFlags_None;
1362
1
    BackendFlags = ImGuiBackendFlags_None;
1363
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1364
1
    DeltaTime = 1.0f / 60.0f;
1365
1
    IniSavingRate = 5.0f;
1366
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1367
1
    LogFilename = "imgui_log.txt";
1368
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1369
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1370
        KeyMap[i] = -1;
1371
#endif
1372
1
    UserData = NULL;
1373
1374
1
    Fonts = NULL;
1375
1
    FontGlobalScale = 1.0f;
1376
1
    FontDefault = NULL;
1377
1
    FontAllowUserScaling = false;
1378
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1379
1380
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1381
1
    ConfigDockingNoSplit = false;
1382
1
    ConfigDockingWithShift = false;
1383
1
    ConfigDockingAlwaysTabBar = false;
1384
1
    ConfigDockingTransparentPayload = false;
1385
1386
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1387
1
    ConfigViewportsNoAutoMerge = false;
1388
1
    ConfigViewportsNoTaskBarIcon = false;
1389
1
    ConfigViewportsNoDecoration = true;
1390
1
    ConfigViewportsNoDefaultParent = false;
1391
1392
    // Miscellaneous options
1393
1
    MouseDrawCursor = false;
1394
#ifdef __APPLE__
1395
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1396
#else
1397
1
    ConfigMacOSXBehaviors = false;
1398
1
#endif
1399
1
    ConfigInputTrickleEventQueue = true;
1400
1
    ConfigInputTextCursorBlink = true;
1401
1
    ConfigInputTextEnterKeepActive = false;
1402
1
    ConfigDragClickToInputText = false;
1403
1
    ConfigWindowsResizeFromEdges = true;
1404
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1405
1
    ConfigMemoryCompactTimer = 60.0f;
1406
1
    ConfigDebugBeginReturnValueOnce = false;
1407
1
    ConfigDebugBeginReturnValueLoop = false;
1408
1409
    // Inputs Behaviors
1410
1
    MouseDoubleClickTime = 0.30f;
1411
1
    MouseDoubleClickMaxDist = 6.0f;
1412
1
    MouseDragThreshold = 6.0f;
1413
1
    KeyRepeatDelay = 0.275f;
1414
1
    KeyRepeatRate = 0.050f;
1415
1416
    // Platform Functions
1417
    // Note: Initialize() will setup default clipboard/ime handlers.
1418
1
    BackendPlatformName = BackendRendererName = NULL;
1419
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1420
1
    PlatformOpenInShellUserData = NULL;
1421
1
    PlatformLocaleDecimalPoint = '.';
1422
1423
    // Input (NB: we already have memset zero the entire structure!)
1424
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1425
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1426
1
    MouseSource = ImGuiMouseSource_Mouse;
1427
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1428
155
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1429
1
    AppAcceptingEvents = true;
1430
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1431
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1432
1
}
1433
1434
// Pass in translated ASCII characters for text input.
1435
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1436
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1437
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1438
void ImGuiIO::AddInputCharacter(unsigned int c)
1439
6.50k
{
1440
6.50k
    IM_ASSERT(Ctx != NULL);
1441
6.50k
    ImGuiContext& g = *Ctx;
1442
6.50k
    if (c == 0 || !AppAcceptingEvents)
1443
1.33k
        return;
1444
1445
5.17k
    ImGuiInputEvent e;
1446
5.17k
    e.Type = ImGuiInputEventType_Text;
1447
5.17k
    e.Source = ImGuiInputSource_Keyboard;
1448
5.17k
    e.EventId = g.InputEventsNextEventId++;
1449
5.17k
    e.Text.Char = c;
1450
5.17k
    g.InputEventsQueue.push_back(e);
1451
5.17k
}
1452
1453
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1454
// we should save the high surrogate.
1455
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1456
1.80k
{
1457
1.80k
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1458
132
        return;
1459
1460
1.67k
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1461
646
    {
1462
646
        if (InputQueueSurrogate != 0)
1463
193
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1464
646
        InputQueueSurrogate = c;
1465
646
        return;
1466
646
    }
1467
1468
1.03k
    ImWchar cp = c;
1469
1.03k
    if (InputQueueSurrogate != 0)
1470
442
    {
1471
442
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1472
392
        {
1473
392
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1474
392
        }
1475
50
        else
1476
50
        {
1477
50
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1478
50
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1479
#else
1480
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1481
#endif
1482
50
        }
1483
1484
442
        InputQueueSurrogate = 0;
1485
442
    }
1486
1.03k
    AddInputCharacter((unsigned)cp);
1487
1.03k
}
1488
1489
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1490
48
{
1491
48
    if (!AppAcceptingEvents)
1492
0
        return;
1493
48
    while (*utf8_chars != 0)
1494
0
    {
1495
0
        unsigned int c = 0;
1496
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1497
0
        AddInputCharacter(c);
1498
0
    }
1499
48
}
1500
1501
// Clear all incoming events.
1502
void ImGuiIO::ClearEventsQueue()
1503
0
{
1504
0
    IM_ASSERT(Ctx != NULL);
1505
0
    ImGuiContext& g = *Ctx;
1506
0
    g.InputEventsQueue.clear();
1507
0
}
1508
1509
// Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1510
void ImGuiIO::ClearInputKeys()
1511
13.6k
{
1512
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1513
    memset(KeysDown, 0, sizeof(KeysDown));
1514
#endif
1515
2.11M
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1516
2.10M
    {
1517
2.10M
        if (ImGui::IsMouseKey((ImGuiKey)(n + ImGuiKey_KeysData_OFFSET)))
1518
95.5k
            continue;
1519
2.00M
        KeysData[n].Down             = false;
1520
2.00M
        KeysData[n].DownDuration     = -1.0f;
1521
2.00M
        KeysData[n].DownDurationPrev = -1.0f;
1522
2.00M
    }
1523
13.6k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1524
13.6k
    KeyMods = ImGuiMod_None;
1525
13.6k
    InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1526
13.6k
}
1527
1528
void ImGuiIO::ClearInputMouse()
1529
3.92k
{
1530
31.3k
    for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1))
1531
27.4k
    {
1532
27.4k
        ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_KeysData_OFFSET];
1533
27.4k
        key_data->Down = false;
1534
27.4k
        key_data->DownDuration = -1.0f;
1535
27.4k
        key_data->DownDurationPrev = -1.0f;
1536
27.4k
    }
1537
3.92k
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1538
23.5k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1539
19.6k
    {
1540
19.6k
        MouseDown[n] = false;
1541
19.6k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1542
19.6k
    }
1543
3.92k
    MouseWheel = MouseWheelH = 0.0f;
1544
3.92k
}
1545
1546
// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1547
// Current frame character buffer is now also cleared by ClearInputKeys().
1548
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1549
void ImGuiIO::ClearInputCharacters()
1550
{
1551
    InputQueueCharacters.resize(0);
1552
}
1553
#endif
1554
1555
static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1556
32.2k
{
1557
32.2k
    ImGuiContext& g = *ctx;
1558
54.6k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1559
34.2k
    {
1560
34.2k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1561
34.2k
        if (e->Type != type)
1562
18.6k
            continue;
1563
15.5k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1564
2.43k
            continue;
1565
13.1k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1566
1.25k
            continue;
1567
11.8k
        return e;
1568
13.1k
    }
1569
20.4k
    return NULL;
1570
32.2k
}
1571
1572
// Queue a new key down/up event.
1573
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1574
// - bool down:          Is the key down? use false to signify a key release.
1575
// - float analog_value: 0.0f..1.0f
1576
// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1577
// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1578
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1579
8.14k
{
1580
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1581
8.14k
    IM_ASSERT(Ctx != NULL);
1582
8.14k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1583
0
        return;
1584
8.14k
    ImGuiContext& g = *Ctx;
1585
8.14k
    IM_ASSERT(ImGui::IsNamedKeyOrMod(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1586
8.14k
    IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1587
1588
    // MacOS: swap Cmd(Super) and Ctrl
1589
8.14k
    if (g.IO.ConfigMacOSXBehaviors)
1590
0
    {
1591
0
        if (key == ImGuiMod_Super)          { key = ImGuiMod_Ctrl; }
1592
0
        else if (key == ImGuiMod_Ctrl)      { key = ImGuiMod_Super; }
1593
0
        else if (key == ImGuiKey_LeftSuper) { key = ImGuiKey_LeftCtrl; }
1594
0
        else if (key == ImGuiKey_RightSuper){ key = ImGuiKey_RightCtrl; }
1595
0
        else if (key == ImGuiKey_LeftCtrl)  { key = ImGuiKey_LeftSuper; }
1596
0
        else if (key == ImGuiKey_RightCtrl) { key = ImGuiKey_RightSuper; }
1597
0
    }
1598
1599
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1600
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1601
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1602
    if (BackendUsingLegacyKeyArrays == -1)
1603
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1604
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1605
    BackendUsingLegacyKeyArrays = 0;
1606
#endif
1607
8.14k
    if (ImGui::IsGamepadKey(key))
1608
94
        BackendUsingLegacyNavInputArray = false;
1609
1610
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1611
8.14k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1612
8.14k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1613
8.14k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1614
8.14k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1615
8.14k
    if (latest_key_down == down && latest_key_analog == analog_value)
1616
901
        return;
1617
1618
    // Add event
1619
7.24k
    ImGuiInputEvent e;
1620
7.24k
    e.Type = ImGuiInputEventType_Key;
1621
7.24k
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1622
7.24k
    e.EventId = g.InputEventsNextEventId++;
1623
7.24k
    e.Key.Key = key;
1624
7.24k
    e.Key.Down = down;
1625
7.24k
    e.Key.AnalogValue = analog_value;
1626
7.24k
    g.InputEventsQueue.push_back(e);
1627
7.24k
}
1628
1629
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1630
1.35k
{
1631
1.35k
    if (!AppAcceptingEvents)
1632
0
        return;
1633
1.35k
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1634
1.35k
}
1635
1636
// [Optional] Call after AddKeyEvent().
1637
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1638
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1639
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1640
0
{
1641
0
    if (key == ImGuiKey_None)
1642
0
        return;
1643
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1644
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1645
0
    IM_UNUSED(native_keycode);  // Yet unused
1646
0
    IM_UNUSED(native_scancode); // Yet unused
1647
1648
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1649
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1650
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1651
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1652
        return;
1653
    KeyMap[legacy_key] = key;
1654
    KeyMap[key] = legacy_key;
1655
#else
1656
0
    IM_UNUSED(key);
1657
0
    IM_UNUSED(native_legacy_index);
1658
0
#endif
1659
0
}
1660
1661
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1662
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1663
0
{
1664
0
    AppAcceptingEvents = accepting_events;
1665
0
}
1666
1667
// Queue a mouse move event
1668
void ImGuiIO::AddMousePosEvent(float x, float y)
1669
5.29k
{
1670
5.29k
    IM_ASSERT(Ctx != NULL);
1671
5.29k
    ImGuiContext& g = *Ctx;
1672
5.29k
    if (!AppAcceptingEvents)
1673
0
        return;
1674
1675
    // Apply same flooring as UpdateMouseInputs()
1676
5.29k
    ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1677
1678
    // Filter duplicate
1679
5.29k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1680
5.29k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1681
5.29k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1682
932
        return;
1683
1684
4.36k
    ImGuiInputEvent e;
1685
4.36k
    e.Type = ImGuiInputEventType_MousePos;
1686
4.36k
    e.Source = ImGuiInputSource_Mouse;
1687
4.36k
    e.EventId = g.InputEventsNextEventId++;
1688
4.36k
    e.MousePos.PosX = pos.x;
1689
4.36k
    e.MousePos.PosY = pos.y;
1690
4.36k
    e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1691
4.36k
    g.InputEventsQueue.push_back(e);
1692
4.36k
}
1693
1694
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1695
14.0k
{
1696
14.0k
    IM_ASSERT(Ctx != NULL);
1697
14.0k
    ImGuiContext& g = *Ctx;
1698
14.0k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1699
14.0k
    if (!AppAcceptingEvents)
1700
0
        return;
1701
1702
    // On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button.
1703
14.0k
    if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick)
1704
0
    {
1705
        // Order of both statements matterns: this event will still release mouse button 1
1706
0
        mouse_button = 1;
1707
0
        if (!down)
1708
0
            MouseCtrlLeftAsRightClick = false;
1709
0
    }
1710
1711
    // Filter duplicate
1712
14.0k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1713
14.0k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1714
14.0k
    if (latest_button_down == down)
1715
4.73k
        return;
1716
1717
    // On MacOS X: Convert Ctrl(Super)+Left click into Right-click.
1718
    // - Note that this is actual physical Ctrl which is ImGuiMod_Super for us.
1719
    // - At this point we want from !down to down, so this is handling the initial press.
1720
9.30k
    if (ConfigMacOSXBehaviors && mouse_button == 0 && down)
1721
0
    {
1722
0
        const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super);
1723
0
        if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper)
1724
0
        {
1725
0
            IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n");
1726
0
            MouseCtrlLeftAsRightClick = true;
1727
0
            AddMouseButtonEvent(1, true); // This is just quicker to write that passing through, as we need to filter duplicate again.
1728
0
            return;
1729
0
        }
1730
0
    }
1731
1732
9.30k
    ImGuiInputEvent e;
1733
9.30k
    e.Type = ImGuiInputEventType_MouseButton;
1734
9.30k
    e.Source = ImGuiInputSource_Mouse;
1735
9.30k
    e.EventId = g.InputEventsNextEventId++;
1736
9.30k
    e.MouseButton.Button = mouse_button;
1737
9.30k
    e.MouseButton.Down = down;
1738
9.30k
    e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1739
9.30k
    g.InputEventsQueue.push_back(e);
1740
9.30k
}
1741
1742
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1743
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1744
3.54k
{
1745
3.54k
    IM_ASSERT(Ctx != NULL);
1746
3.54k
    ImGuiContext& g = *Ctx;
1747
1748
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1749
3.54k
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1750
209
        return;
1751
1752
3.33k
    ImGuiInputEvent e;
1753
3.33k
    e.Type = ImGuiInputEventType_MouseWheel;
1754
3.33k
    e.Source = ImGuiInputSource_Mouse;
1755
3.33k
    e.EventId = g.InputEventsNextEventId++;
1756
3.33k
    e.MouseWheel.WheelX = wheel_x;
1757
3.33k
    e.MouseWheel.WheelY = wheel_y;
1758
3.33k
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1759
3.33k
    g.InputEventsQueue.push_back(e);
1760
3.33k
}
1761
1762
// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1763
// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1764
void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1765
0
{
1766
0
    IM_ASSERT(Ctx != NULL);
1767
0
    ImGuiContext& g = *Ctx;
1768
0
    g.InputEventsNextMouseSource = source;
1769
0
}
1770
1771
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1772
0
{
1773
0
    IM_ASSERT(Ctx != NULL);
1774
0
    ImGuiContext& g = *Ctx;
1775
    //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1776
0
    if (!AppAcceptingEvents)
1777
0
        return;
1778
1779
    // Filter duplicate
1780
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1781
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1782
0
    if (latest_viewport_id == viewport_id)
1783
0
        return;
1784
1785
0
    ImGuiInputEvent e;
1786
0
    e.Type = ImGuiInputEventType_MouseViewport;
1787
0
    e.Source = ImGuiInputSource_Mouse;
1788
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1789
0
    g.InputEventsQueue.push_back(e);
1790
0
}
1791
1792
void ImGuiIO::AddFocusEvent(bool focused)
1793
4.81k
{
1794
4.81k
    IM_ASSERT(Ctx != NULL);
1795
4.81k
    ImGuiContext& g = *Ctx;
1796
1797
    // Filter duplicate
1798
4.81k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1799
4.81k
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1800
4.81k
    if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1801
641
        return;
1802
1803
4.17k
    ImGuiInputEvent e;
1804
4.17k
    e.Type = ImGuiInputEventType_Focus;
1805
4.17k
    e.EventId = g.InputEventsNextEventId++;
1806
4.17k
    e.AppFocused.Focused = focused;
1807
4.17k
    g.InputEventsQueue.push_back(e);
1808
4.17k
}
1809
1810
//-----------------------------------------------------------------------------
1811
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1812
//-----------------------------------------------------------------------------
1813
1814
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1815
0
{
1816
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1817
0
    ImVec2 p_last = p1;
1818
0
    ImVec2 p_closest;
1819
0
    float p_closest_dist2 = FLT_MAX;
1820
0
    float t_step = 1.0f / (float)num_segments;
1821
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1822
0
    {
1823
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1824
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1825
0
        float dist2 = ImLengthSqr(p - p_line);
1826
0
        if (dist2 < p_closest_dist2)
1827
0
        {
1828
0
            p_closest = p_line;
1829
0
            p_closest_dist2 = dist2;
1830
0
        }
1831
0
        p_last = p_current;
1832
0
    }
1833
0
    return p_closest;
1834
0
}
1835
1836
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1837
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1838
0
{
1839
0
    float dx = x4 - x1;
1840
0
    float dy = y4 - y1;
1841
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1842
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1843
0
    d2 = (d2 >= 0) ? d2 : -d2;
1844
0
    d3 = (d3 >= 0) ? d3 : -d3;
1845
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1846
0
    {
1847
0
        ImVec2 p_current(x4, y4);
1848
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1849
0
        float dist2 = ImLengthSqr(p - p_line);
1850
0
        if (dist2 < p_closest_dist2)
1851
0
        {
1852
0
            p_closest = p_line;
1853
0
            p_closest_dist2 = dist2;
1854
0
        }
1855
0
        p_last = p_current;
1856
0
    }
1857
0
    else if (level < 10)
1858
0
    {
1859
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1860
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1861
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1862
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1863
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1864
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1865
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1866
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1867
0
    }
1868
0
}
1869
1870
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1871
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1872
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1873
0
{
1874
0
    IM_ASSERT(tess_tol > 0.0f);
1875
0
    ImVec2 p_last = p1;
1876
0
    ImVec2 p_closest;
1877
0
    float p_closest_dist2 = FLT_MAX;
1878
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1879
0
    return p_closest;
1880
0
}
1881
1882
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1883
0
{
1884
0
    ImVec2 ap = p - a;
1885
0
    ImVec2 ab_dir = b - a;
1886
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1887
0
    if (dot < 0.0f)
1888
0
        return a;
1889
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1890
0
    if (dot > ab_len_sqr)
1891
0
        return b;
1892
0
    return a + ab_dir * dot / ab_len_sqr;
1893
0
}
1894
1895
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1896
0
{
1897
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1898
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1899
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1900
0
    return ((b1 == b2) && (b2 == b3));
1901
0
}
1902
1903
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1904
0
{
1905
0
    ImVec2 v0 = b - a;
1906
0
    ImVec2 v1 = c - a;
1907
0
    ImVec2 v2 = p - a;
1908
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1909
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1910
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1911
0
    out_u = 1.0f - out_v - out_w;
1912
0
}
1913
1914
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1915
0
{
1916
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1917
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1918
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1919
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1920
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1921
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1922
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1923
0
    if (m == dist2_ab)
1924
0
        return proj_ab;
1925
0
    if (m == dist2_bc)
1926
0
        return proj_bc;
1927
0
    return proj_ca;
1928
0
}
1929
1930
//-----------------------------------------------------------------------------
1931
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1932
//-----------------------------------------------------------------------------
1933
1934
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1935
int ImStricmp(const char* str1, const char* str2)
1936
0
{
1937
0
    int d;
1938
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1939
0
    return d;
1940
0
}
1941
1942
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1943
0
{
1944
0
    int d = 0;
1945
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1946
0
    return d;
1947
0
}
1948
1949
void ImStrncpy(char* dst, const char* src, size_t count)
1950
16
{
1951
16
    if (count < 1)
1952
0
        return;
1953
16
    if (count > 1)
1954
16
        strncpy(dst, src, count - 1);
1955
16
    dst[count - 1] = 0;
1956
16
}
1957
1958
char* ImStrdup(const char* str)
1959
3
{
1960
3
    size_t len = strlen(str);
1961
3
    void* buf = IM_ALLOC(len + 1);
1962
3
    return (char*)memcpy(buf, (const void*)str, len + 1);
1963
3
}
1964
1965
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1966
0
{
1967
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1968
0
    size_t src_size = strlen(src) + 1;
1969
0
    if (dst_buf_size < src_size)
1970
0
    {
1971
0
        IM_FREE(dst);
1972
0
        dst = (char*)IM_ALLOC(src_size);
1973
0
        if (p_dst_size)
1974
0
            *p_dst_size = src_size;
1975
0
    }
1976
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1977
0
}
1978
1979
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1980
0
{
1981
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1982
0
    return p;
1983
0
}
1984
1985
int ImStrlenW(const ImWchar* str)
1986
0
{
1987
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1988
0
    int n = 0;
1989
0
    while (*str++) n++;
1990
0
    return n;
1991
0
}
1992
1993
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1994
const char* ImStreolRange(const char* str, const char* str_end)
1995
0
{
1996
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1997
0
    return p ? p : str_end;
1998
0
}
1999
2000
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
2001
0
{
2002
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
2003
0
        buf_mid_line--;
2004
0
    return buf_mid_line;
2005
0
}
2006
2007
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
2008
0
{
2009
0
    if (!needle_end)
2010
0
        needle_end = needle + strlen(needle);
2011
2012
0
    const char un0 = (char)ImToUpper(*needle);
2013
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
2014
0
    {
2015
0
        if (ImToUpper(*haystack) == un0)
2016
0
        {
2017
0
            const char* b = needle + 1;
2018
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
2019
0
                if (ImToUpper(*a) != ImToUpper(*b))
2020
0
                    break;
2021
0
            if (b == needle_end)
2022
0
                return haystack;
2023
0
        }
2024
0
        haystack++;
2025
0
    }
2026
0
    return NULL;
2027
0
}
2028
2029
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
2030
void ImStrTrimBlanks(char* buf)
2031
0
{
2032
0
    char* p = buf;
2033
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
2034
0
        p++;
2035
0
    char* p_start = p;
2036
0
    while (*p != 0)                         // Find end of string
2037
0
        p++;
2038
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
2039
0
        p--;
2040
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
2041
0
        memmove(buf, p_start, p - p_start);
2042
0
    buf[p - p_start] = 0;                   // Zero terminate
2043
0
}
2044
2045
const char* ImStrSkipBlank(const char* str)
2046
0
{
2047
0
    while (str[0] == ' ' || str[0] == '\t')
2048
0
        str++;
2049
0
    return str;
2050
0
}
2051
2052
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
2053
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
2054
// B) When buf==NULL vsnprintf() will return the output size.
2055
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2056
2057
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
2058
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2059
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
2060
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
2061
#ifdef IMGUI_USE_STB_SPRINTF
2062
#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
2063
#define STB_SPRINTF_IMPLEMENTATION
2064
#endif
2065
#ifdef IMGUI_STB_SPRINTF_FILENAME
2066
#include IMGUI_STB_SPRINTF_FILENAME
2067
#else
2068
#include "stb_sprintf.h"
2069
#endif
2070
#endif // #ifdef IMGUI_USE_STB_SPRINTF
2071
2072
#if defined(_MSC_VER) && !defined(vsnprintf)
2073
#define vsnprintf _vsnprintf
2074
#endif
2075
2076
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
2077
1
{
2078
1
    va_list args;
2079
1
    va_start(args, fmt);
2080
#ifdef IMGUI_USE_STB_SPRINTF
2081
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2082
#else
2083
1
    int w = vsnprintf(buf, buf_size, fmt, args);
2084
1
#endif
2085
1
    va_end(args);
2086
1
    if (buf == NULL)
2087
0
        return w;
2088
1
    if (w == -1 || w >= (int)buf_size)
2089
0
        w = (int)buf_size - 1;
2090
1
    buf[w] = 0;
2091
1
    return w;
2092
1
}
2093
2094
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
2095
11.4k
{
2096
#ifdef IMGUI_USE_STB_SPRINTF
2097
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2098
#else
2099
11.4k
    int w = vsnprintf(buf, buf_size, fmt, args);
2100
11.4k
#endif
2101
11.4k
    if (buf == NULL)
2102
0
        return w;
2103
11.4k
    if (w == -1 || w >= (int)buf_size)
2104
0
        w = (int)buf_size - 1;
2105
11.4k
    buf[w] = 0;
2106
11.4k
    return w;
2107
11.4k
}
2108
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2109
2110
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2111
11.4k
{
2112
11.4k
    va_list args;
2113
11.4k
    va_start(args, fmt);
2114
11.4k
    ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2115
11.4k
    va_end(args);
2116
11.4k
}
2117
2118
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2119
11.4k
{
2120
11.4k
    ImGuiContext& g = *GImGui;
2121
11.4k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2122
0
    {
2123
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2124
0
        if (buf == NULL)
2125
0
            buf = "(null)";
2126
0
        *out_buf = buf;
2127
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
2128
0
    }
2129
11.4k
    else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2130
0
    {
2131
0
        int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2132
0
        const char* buf = va_arg(args, const char*);
2133
0
        if (buf == NULL)
2134
0
        {
2135
0
            buf = "(null)";
2136
0
            buf_len = ImMin(buf_len, 6);
2137
0
        }
2138
0
        *out_buf = buf;
2139
0
        *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2140
0
    }
2141
11.4k
    else
2142
11.4k
    {
2143
11.4k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2144
11.4k
        *out_buf = g.TempBuffer.Data;
2145
11.4k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2146
11.4k
    }
2147
11.4k
}
2148
2149
// CRC32 needs a 1KB lookup table (not cache friendly)
2150
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2151
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2152
static const ImU32 GCrc32LookupTable[256] =
2153
{
2154
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2155
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2156
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2157
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2158
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2159
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2160
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2161
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2162
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2163
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2164
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2165
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2166
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2167
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2168
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2169
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2170
};
2171
2172
// Known size hash
2173
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2174
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2175
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2176
68.9k
{
2177
68.9k
    ImU32 crc = ~seed;
2178
68.9k
    const unsigned char* data = (const unsigned char*)data_p;
2179
68.9k
    const ImU32* crc32_lut = GCrc32LookupTable;
2180
344k
    while (data_size-- != 0)
2181
275k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2182
68.9k
    return ~crc;
2183
68.9k
}
2184
2185
// Zero-terminated string hash, with support for ### to reset back to seed value
2186
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2187
// Because this syntax is rarely used we are optimizing for the common case.
2188
// - If we reach ### in the string we discard the hash so far and reset to the seed.
2189
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2190
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2191
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2192
462k
{
2193
462k
    seed = ~seed;
2194
462k
    ImU32 crc = seed;
2195
462k
    const unsigned char* data = (const unsigned char*)data_p;
2196
462k
    const ImU32* crc32_lut = GCrc32LookupTable;
2197
462k
    if (data_size != 0)
2198
0
    {
2199
0
        while (data_size-- != 0)
2200
0
        {
2201
0
            unsigned char c = *data++;
2202
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2203
0
                crc = seed;
2204
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2205
0
        }
2206
0
    }
2207
462k
    else
2208
462k
    {
2209
6.34M
        while (unsigned char c = *data++)
2210
5.88M
        {
2211
5.88M
            if (c == '#' && data[0] == '#' && data[1] == '#')
2212
79.1k
                crc = seed;
2213
5.88M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2214
5.88M
        }
2215
462k
    }
2216
462k
    return ~crc;
2217
462k
}
2218
2219
//-----------------------------------------------------------------------------
2220
// [SECTION] MISC HELPERS/UTILITIES (File functions)
2221
//-----------------------------------------------------------------------------
2222
2223
// Default file functions
2224
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2225
2226
ImFileHandle ImFileOpen(const char* filename, const char* mode)
2227
0
{
2228
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2229
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2230
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2231
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2232
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2233
2234
    // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2235
    // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2236
    wchar_t local_temp_stack[FILENAME_MAX];
2237
    ImVector<wchar_t> local_temp_heap;
2238
    if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2239
        local_temp_heap.resize(filename_wsize + mode_wsize);
2240
    wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2241
    wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2242
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2243
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2244
    return ::_wfopen(filename_wbuf, mode_wbuf);
2245
#else
2246
0
    return fopen(filename, mode);
2247
0
#endif
2248
0
}
2249
2250
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2251
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
2252
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2253
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2254
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2255
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2256
2257
// Helper: Load file content into memory
2258
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2259
// This can't really be used with "rt" because fseek size won't match read size.
2260
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2261
0
{
2262
0
    IM_ASSERT(filename && mode);
2263
0
    if (out_file_size)
2264
0
        *out_file_size = 0;
2265
2266
0
    ImFileHandle f;
2267
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2268
0
        return NULL;
2269
2270
0
    size_t file_size = (size_t)ImFileGetSize(f);
2271
0
    if (file_size == (size_t)-1)
2272
0
    {
2273
0
        ImFileClose(f);
2274
0
        return NULL;
2275
0
    }
2276
2277
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2278
0
    if (file_data == NULL)
2279
0
    {
2280
0
        ImFileClose(f);
2281
0
        return NULL;
2282
0
    }
2283
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2284
0
    {
2285
0
        ImFileClose(f);
2286
0
        IM_FREE(file_data);
2287
0
        return NULL;
2288
0
    }
2289
0
    if (padding_bytes > 0)
2290
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2291
2292
0
    ImFileClose(f);
2293
0
    if (out_file_size)
2294
0
        *out_file_size = file_size;
2295
2296
0
    return file_data;
2297
0
}
2298
2299
//-----------------------------------------------------------------------------
2300
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2301
//-----------------------------------------------------------------------------
2302
2303
IM_MSVC_RUNTIME_CHECKS_OFF
2304
2305
// Convert UTF-8 to 32-bit character, process single character input.
2306
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2307
// We handle UTF-8 decoding error by skipping forward.
2308
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2309
149k
{
2310
149k
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2311
149k
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2312
149k
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2313
149k
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2314
149k
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2315
149k
    int len = lengths[*(const unsigned char*)in_text >> 3];
2316
149k
    int wanted = len + (len ? 0 : 1);
2317
2318
149k
    if (in_text_end == NULL)
2319
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2320
2321
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2322
    // so it is fast even with excessive branching.
2323
149k
    unsigned char s[4];
2324
149k
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2325
149k
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2326
149k
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2327
149k
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2328
2329
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2330
149k
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2331
149k
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2332
149k
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2333
149k
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2334
149k
    *out_char >>= shiftc[len];
2335
2336
    // Accumulate the various error conditions.
2337
149k
    int e = 0;
2338
149k
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2339
149k
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2340
149k
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2341
149k
    e |= (s[1] & 0xc0) >> 2;
2342
149k
    e |= (s[2] & 0xc0) >> 4;
2343
149k
    e |= (s[3]       ) >> 6;
2344
149k
    e ^= 0x2a; // top two bits of each tail byte correct?
2345
149k
    e >>= shifte[len];
2346
2347
149k
    if (e)
2348
57.2k
    {
2349
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2350
        // One byte is consumed in case of invalid first byte of in_text.
2351
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2352
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2353
57.2k
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2354
57.2k
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2355
57.2k
    }
2356
2357
149k
    return wanted;
2358
149k
}
2359
2360
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2361
0
{
2362
0
    ImWchar* buf_out = buf;
2363
0
    ImWchar* buf_end = buf + buf_size;
2364
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2365
0
    {
2366
0
        unsigned int c;
2367
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2368
0
        *buf_out++ = (ImWchar)c;
2369
0
    }
2370
0
    *buf_out = 0;
2371
0
    if (in_text_remaining)
2372
0
        *in_text_remaining = in_text;
2373
0
    return (int)(buf_out - buf);
2374
0
}
2375
2376
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2377
0
{
2378
0
    int char_count = 0;
2379
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2380
0
    {
2381
0
        unsigned int c;
2382
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2383
0
        char_count++;
2384
0
    }
2385
0
    return char_count;
2386
0
}
2387
2388
// Based on stb_to_utf8() from github.com/nothings/stb/
2389
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2390
0
{
2391
0
    if (c < 0x80)
2392
0
    {
2393
0
        buf[0] = (char)c;
2394
0
        return 1;
2395
0
    }
2396
0
    if (c < 0x800)
2397
0
    {
2398
0
        if (buf_size < 2) return 0;
2399
0
        buf[0] = (char)(0xc0 + (c >> 6));
2400
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2401
0
        return 2;
2402
0
    }
2403
0
    if (c < 0x10000)
2404
0
    {
2405
0
        if (buf_size < 3) return 0;
2406
0
        buf[0] = (char)(0xe0 + (c >> 12));
2407
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2408
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2409
0
        return 3;
2410
0
    }
2411
0
    if (c <= 0x10FFFF)
2412
0
    {
2413
0
        if (buf_size < 4) return 0;
2414
0
        buf[0] = (char)(0xf0 + (c >> 18));
2415
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2416
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2417
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2418
0
        return 4;
2419
0
    }
2420
    // Invalid code point, the max unicode is 0x10FFFF
2421
0
    return 0;
2422
0
}
2423
2424
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2425
0
{
2426
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2427
0
    out_buf[count] = 0;
2428
0
    return out_buf;
2429
0
}
2430
2431
// Not optimal but we very rarely use this function.
2432
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2433
0
{
2434
0
    unsigned int unused = 0;
2435
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2436
0
}
2437
2438
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2439
0
{
2440
0
    if (c < 0x80) return 1;
2441
0
    if (c < 0x800) return 2;
2442
0
    if (c < 0x10000) return 3;
2443
0
    if (c <= 0x10FFFF) return 4;
2444
0
    return 3;
2445
0
}
2446
2447
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2448
0
{
2449
0
    char* buf_p = out_buf;
2450
0
    const char* buf_end = out_buf + out_buf_size;
2451
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2452
0
    {
2453
0
        unsigned int c = (unsigned int)(*in_text++);
2454
0
        if (c < 0x80)
2455
0
            *buf_p++ = (char)c;
2456
0
        else
2457
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2458
0
    }
2459
0
    *buf_p = 0;
2460
0
    return (int)(buf_p - out_buf);
2461
0
}
2462
2463
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2464
0
{
2465
0
    int bytes_count = 0;
2466
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2467
0
    {
2468
0
        unsigned int c = (unsigned int)(*in_text++);
2469
0
        if (c < 0x80)
2470
0
            bytes_count++;
2471
0
        else
2472
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2473
0
    }
2474
0
    return bytes_count;
2475
0
}
2476
2477
const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2478
0
{
2479
0
    while (in_text_curr > in_text_start)
2480
0
    {
2481
0
        in_text_curr--;
2482
0
        if ((*in_text_curr & 0xC0) != 0x80)
2483
0
            return in_text_curr;
2484
0
    }
2485
0
    return in_text_start;
2486
0
}
2487
2488
int ImTextCountLines(const char* in_text, const char* in_text_end)
2489
0
{
2490
0
    if (in_text_end == NULL)
2491
0
        in_text_end = in_text + strlen(in_text); // FIXME-OPT: Not optimal approach, discourage use for now.
2492
0
    int count = 0;
2493
0
    while (in_text < in_text_end)
2494
0
    {
2495
0
        const char* line_end = (const char*)memchr(in_text, '\n', in_text_end - in_text);
2496
0
        in_text = line_end ? line_end + 1 : in_text_end;
2497
0
        count++;
2498
0
    }
2499
0
    return count;
2500
0
}
2501
2502
IM_MSVC_RUNTIME_CHECKS_RESTORE
2503
2504
//-----------------------------------------------------------------------------
2505
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2506
// Note: The Convert functions are early design which are not consistent with other API.
2507
//-----------------------------------------------------------------------------
2508
2509
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2510
0
{
2511
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2512
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2513
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2514
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2515
0
    return IM_COL32(r, g, b, 0xFF);
2516
0
}
2517
2518
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2519
215k
{
2520
215k
    float s = 1.0f / 255.0f;
2521
215k
    return ImVec4(
2522
215k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2523
215k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2524
215k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2525
215k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2526
215k
}
2527
2528
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2529
1.13M
{
2530
1.13M
    ImU32 out;
2531
1.13M
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2532
1.13M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2533
1.13M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2534
1.13M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2535
1.13M
    return out;
2536
1.13M
}
2537
2538
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2539
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2540
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2541
0
{
2542
0
    float K = 0.f;
2543
0
    if (g < b)
2544
0
    {
2545
0
        ImSwap(g, b);
2546
0
        K = -1.f;
2547
0
    }
2548
0
    if (r < g)
2549
0
    {
2550
0
        ImSwap(r, g);
2551
0
        K = -2.f / 6.f - K;
2552
0
    }
2553
2554
0
    const float chroma = r - (g < b ? g : b);
2555
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2556
0
    out_s = chroma / (r + 1e-20f);
2557
0
    out_v = r;
2558
0
}
2559
2560
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2561
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2562
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2563
0
{
2564
0
    if (s == 0.0f)
2565
0
    {
2566
        // gray
2567
0
        out_r = out_g = out_b = v;
2568
0
        return;
2569
0
    }
2570
2571
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2572
0
    int   i = (int)h;
2573
0
    float f = h - (float)i;
2574
0
    float p = v * (1.0f - s);
2575
0
    float q = v * (1.0f - s * f);
2576
0
    float t = v * (1.0f - s * (1.0f - f));
2577
2578
0
    switch (i)
2579
0
    {
2580
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2581
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2582
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2583
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2584
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2585
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2586
0
    }
2587
0
}
2588
2589
//-----------------------------------------------------------------------------
2590
// [SECTION] ImGuiStorage
2591
// Helper: Key->value storage
2592
//-----------------------------------------------------------------------------
2593
2594
// std::lower_bound but without the bullshit
2595
ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key)
2596
169k
{
2597
169k
    ImGuiStoragePair* in_p = in_begin;
2598
509k
    for (size_t count = (size_t)(in_end - in_p); count > 0; )
2599
339k
    {
2600
339k
        size_t count2 = count >> 1;
2601
339k
        ImGuiStoragePair* mid = in_p + count2;
2602
339k
        if (mid->key < key)
2603
90.5k
        {
2604
90.5k
            in_p = ++mid;
2605
90.5k
            count -= count2 + 1;
2606
90.5k
        }
2607
248k
        else
2608
248k
        {
2609
248k
            count = count2;
2610
248k
        }
2611
339k
    }
2612
169k
    return in_p;
2613
169k
}
2614
2615
static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2616
0
{
2617
    // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2618
0
    ImGuiID lhs_v = ((const ImGuiStoragePair*)lhs)->key;
2619
0
    ImGuiID rhs_v = ((const ImGuiStoragePair*)rhs)->key;
2620
0
    return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0);
2621
0
}
2622
2623
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2624
void ImGuiStorage::BuildSortByKey()
2625
0
{
2626
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), PairComparerByID);
2627
0
}
2628
2629
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2630
0
{
2631
0
    ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2632
0
    if (it == Data.end() || it->key != key)
2633
0
        return default_val;
2634
0
    return it->val_i;
2635
0
}
2636
2637
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2638
0
{
2639
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2640
0
}
2641
2642
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2643
0
{
2644
0
    ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2645
0
    if (it == Data.end() || it->key != key)
2646
0
        return default_val;
2647
0
    return it->val_f;
2648
0
}
2649
2650
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2651
169k
{
2652
169k
    ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2653
169k
    if (it == Data.end() || it->key != key)
2654
3
        return NULL;
2655
169k
    return it->val_p;
2656
169k
}
2657
2658
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2659
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2660
0
{
2661
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2662
0
    if (it == Data.end() || it->key != key)
2663
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2664
0
    return &it->val_i;
2665
0
}
2666
2667
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2668
0
{
2669
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2670
0
}
2671
2672
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2673
0
{
2674
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2675
0
    if (it == Data.end() || it->key != key)
2676
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2677
0
    return &it->val_f;
2678
0
}
2679
2680
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2681
0
{
2682
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2683
0
    if (it == Data.end() || it->key != key)
2684
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2685
0
    return &it->val_p;
2686
0
}
2687
2688
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2689
void ImGuiStorage::SetInt(ImGuiID key, int val)
2690
0
{
2691
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2692
0
    if (it == Data.end() || it->key != key)
2693
0
        Data.insert(it, ImGuiStoragePair(key, val));
2694
0
    else
2695
0
        it->val_i = val;
2696
0
}
2697
2698
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2699
0
{
2700
0
    SetInt(key, val ? 1 : 0);
2701
0
}
2702
2703
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2704
0
{
2705
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2706
0
    if (it == Data.end() || it->key != key)
2707
0
        Data.insert(it, ImGuiStoragePair(key, val));
2708
0
    else
2709
0
        it->val_f = val;
2710
0
}
2711
2712
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2713
3
{
2714
3
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2715
3
    if (it == Data.end() || it->key != key)
2716
3
        Data.insert(it, ImGuiStoragePair(key, val));
2717
0
    else
2718
0
        it->val_p = val;
2719
3
}
2720
2721
void ImGuiStorage::SetAllInt(int v)
2722
0
{
2723
0
    for (int i = 0; i < Data.Size; i++)
2724
0
        Data[i].val_i = v;
2725
0
}
2726
2727
//-----------------------------------------------------------------------------
2728
// [SECTION] ImGuiTextFilter
2729
//-----------------------------------------------------------------------------
2730
2731
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2732
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2733
0
{
2734
0
    InputBuf[0] = 0;
2735
0
    CountGrep = 0;
2736
0
    if (default_filter)
2737
0
    {
2738
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2739
0
        Build();
2740
0
    }
2741
0
}
2742
2743
bool ImGuiTextFilter::Draw(const char* label, float width)
2744
0
{
2745
0
    if (width != 0.0f)
2746
0
        ImGui::SetNextItemWidth(width);
2747
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2748
0
    if (value_changed)
2749
0
        Build();
2750
0
    return value_changed;
2751
0
}
2752
2753
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2754
0
{
2755
0
    out->resize(0);
2756
0
    const char* wb = b;
2757
0
    const char* we = wb;
2758
0
    while (we < e)
2759
0
    {
2760
0
        if (*we == separator)
2761
0
        {
2762
0
            out->push_back(ImGuiTextRange(wb, we));
2763
0
            wb = we + 1;
2764
0
        }
2765
0
        we++;
2766
0
    }
2767
0
    if (wb != we)
2768
0
        out->push_back(ImGuiTextRange(wb, we));
2769
0
}
2770
2771
void ImGuiTextFilter::Build()
2772
0
{
2773
0
    Filters.resize(0);
2774
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2775
0
    input_range.split(',', &Filters);
2776
2777
0
    CountGrep = 0;
2778
0
    for (ImGuiTextRange& f : Filters)
2779
0
    {
2780
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2781
0
            f.b++;
2782
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2783
0
            f.e--;
2784
0
        if (f.empty())
2785
0
            continue;
2786
0
        if (f.b[0] != '-')
2787
0
            CountGrep += 1;
2788
0
    }
2789
0
}
2790
2791
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2792
0
{
2793
0
    if (Filters.empty())
2794
0
        return true;
2795
2796
0
    if (text == NULL)
2797
0
        text = "";
2798
2799
0
    for (const ImGuiTextRange& f : Filters)
2800
0
    {
2801
0
        if (f.empty())
2802
0
            continue;
2803
0
        if (f.b[0] == '-')
2804
0
        {
2805
            // Subtract
2806
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2807
0
                return false;
2808
0
        }
2809
0
        else
2810
0
        {
2811
            // Grep
2812
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2813
0
                return true;
2814
0
        }
2815
0
    }
2816
2817
    // Implicit * grep
2818
0
    if (CountGrep == 0)
2819
0
        return true;
2820
2821
0
    return false;
2822
0
}
2823
2824
//-----------------------------------------------------------------------------
2825
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2826
//-----------------------------------------------------------------------------
2827
2828
// On some platform vsnprintf() takes va_list by reference and modifies it.
2829
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2830
#ifndef va_copy
2831
#if defined(__GNUC__) || defined(__clang__)
2832
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2833
#else
2834
#define va_copy(dest, src) (dest = src)
2835
#endif
2836
#endif
2837
2838
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2839
2840
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2841
0
{
2842
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2843
2844
    // Add zero-terminator the first time
2845
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2846
0
    const int needed_sz = write_off + len;
2847
0
    if (write_off + len >= Buf.Capacity)
2848
0
    {
2849
0
        int new_capacity = Buf.Capacity * 2;
2850
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2851
0
    }
2852
2853
0
    Buf.resize(needed_sz);
2854
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2855
0
    Buf[write_off - 1 + len] = 0;
2856
0
}
2857
2858
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2859
0
{
2860
0
    va_list args;
2861
0
    va_start(args, fmt);
2862
0
    appendfv(fmt, args);
2863
0
    va_end(args);
2864
0
}
2865
2866
// Helper: Text buffer for logging/accumulating text
2867
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2868
0
{
2869
0
    va_list args_copy;
2870
0
    va_copy(args_copy, args);
2871
2872
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2873
0
    if (len <= 0)
2874
0
    {
2875
0
        va_end(args_copy);
2876
0
        return;
2877
0
    }
2878
2879
    // Add zero-terminator the first time
2880
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2881
0
    const int needed_sz = write_off + len;
2882
0
    if (write_off + len >= Buf.Capacity)
2883
0
    {
2884
0
        int new_capacity = Buf.Capacity * 2;
2885
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2886
0
    }
2887
2888
0
    Buf.resize(needed_sz);
2889
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2890
0
    va_end(args_copy);
2891
0
}
2892
2893
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2894
0
{
2895
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2896
0
    if (old_size == new_size)
2897
0
        return;
2898
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2899
0
        LineOffsets.push_back(EndOffset);
2900
0
    const char* base_end = base + new_size;
2901
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2902
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2903
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2904
0
    EndOffset = ImMax(EndOffset, new_size);
2905
0
}
2906
2907
//-----------------------------------------------------------------------------
2908
// [SECTION] ImGuiListClipper
2909
//-----------------------------------------------------------------------------
2910
2911
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2912
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2913
static bool GetSkipItemForListClipping()
2914
0
{
2915
0
    ImGuiContext& g = *GImGui;
2916
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2917
0
}
2918
2919
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2920
0
{
2921
0
    if (ranges.Size - offset <= 1)
2922
0
        return;
2923
2924
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2925
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2926
0
        for (int i = offset; i < sort_end + offset; ++i)
2927
0
            if (ranges[i].Min > ranges[i + 1].Min)
2928
0
                ImSwap(ranges[i], ranges[i + 1]);
2929
2930
    // Now fuse ranges together as much as possible.
2931
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2932
0
    {
2933
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2934
0
        if (ranges[i - 1].Max < ranges[i].Min)
2935
0
            continue;
2936
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2937
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2938
0
        ranges.erase(ranges.Data + i);
2939
0
        i--;
2940
0
    }
2941
0
}
2942
2943
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2944
0
{
2945
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2946
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2947
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2948
0
    ImGuiContext& g = *GImGui;
2949
0
    ImGuiWindow* window = g.CurrentWindow;
2950
0
    float off_y = pos_y - window->DC.CursorPos.y;
2951
0
    window->DC.CursorPos.y = pos_y;
2952
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2953
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2954
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2955
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2956
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2957
0
    if (ImGuiTable* table = g.CurrentTable)
2958
0
    {
2959
0
        if (table->IsInsideRow)
2960
0
            ImGui::TableEndRow(table);
2961
0
        table->RowPosY2 = window->DC.CursorPos.y;
2962
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2963
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2964
0
        table->RowBgColorCounter += row_increase;
2965
0
    }
2966
0
}
2967
2968
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2969
0
{
2970
    // StartPosY starts from ItemsFrozen hence the subtraction
2971
    // Perform the add and multiply with double to allow seeking through larger ranges
2972
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2973
0
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2974
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2975
0
}
2976
2977
ImGuiListClipper::ImGuiListClipper()
2978
0
{
2979
0
    memset(this, 0, sizeof(*this));
2980
0
}
2981
2982
ImGuiListClipper::~ImGuiListClipper()
2983
0
{
2984
0
    End();
2985
0
}
2986
2987
void ImGuiListClipper::Begin(int items_count, float items_height)
2988
0
{
2989
0
    if (Ctx == NULL)
2990
0
        Ctx = ImGui::GetCurrentContext();
2991
2992
0
    ImGuiContext& g = *Ctx;
2993
0
    ImGuiWindow* window = g.CurrentWindow;
2994
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2995
2996
0
    if (ImGuiTable* table = g.CurrentTable)
2997
0
        if (table->IsInsideRow)
2998
0
            ImGui::TableEndRow(table);
2999
3000
0
    StartPosY = window->DC.CursorPos.y;
3001
0
    ItemsHeight = items_height;
3002
0
    ItemsCount = items_count;
3003
0
    DisplayStart = -1;
3004
0
    DisplayEnd = 0;
3005
3006
    // Acquire temporary buffer
3007
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
3008
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
3009
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3010
0
    data->Reset(this);
3011
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
3012
0
    TempData = data;
3013
0
}
3014
3015
void ImGuiListClipper::End()
3016
0
{
3017
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
3018
0
    {
3019
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
3020
0
        ImGuiContext& g = *Ctx;
3021
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
3022
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
3023
0
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
3024
3025
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
3026
0
        IM_ASSERT(data->ListClipper == this);
3027
0
        data->StepNo = data->Ranges.Size;
3028
0
        if (--g.ClipperTempDataStacked > 0)
3029
0
        {
3030
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3031
0
            data->ListClipper->TempData = data;
3032
0
        }
3033
0
        TempData = NULL;
3034
0
    }
3035
0
    ItemsCount = -1;
3036
0
}
3037
3038
void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
3039
0
{
3040
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
3041
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
3042
0
    IM_ASSERT(item_begin <= item_end);
3043
0
    if (item_begin < item_end)
3044
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
3045
0
}
3046
3047
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
3048
0
{
3049
0
    ImGuiContext& g = *clipper->Ctx;
3050
0
    ImGuiWindow* window = g.CurrentWindow;
3051
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
3052
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
3053
3054
0
    ImGuiTable* table = g.CurrentTable;
3055
0
    if (table && table->IsInsideRow)
3056
0
        ImGui::TableEndRow(table);
3057
3058
    // No items
3059
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
3060
0
        return false;
3061
3062
    // While we are in frozen row state, keep displaying items one by one, unclipped
3063
    // FIXME: Could be stored as a table-agnostic state.
3064
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
3065
0
    {
3066
0
        clipper->DisplayStart = data->ItemsFrozen;
3067
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
3068
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
3069
0
            data->ItemsFrozen++;
3070
0
        return true;
3071
0
    }
3072
3073
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
3074
0
    bool calc_clipping = false;
3075
0
    if (data->StepNo == 0)
3076
0
    {
3077
0
        clipper->StartPosY = window->DC.CursorPos.y;
3078
0
        if (clipper->ItemsHeight <= 0.0f)
3079
0
        {
3080
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
3081
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
3082
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
3083
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
3084
0
            data->StepNo = 1;
3085
0
            return true;
3086
0
        }
3087
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
3088
0
    }
3089
3090
    // Step 1: Let the clipper infer height from first range
3091
0
    if (clipper->ItemsHeight <= 0.0f)
3092
0
    {
3093
0
        IM_ASSERT(data->StepNo == 1);
3094
0
        if (table)
3095
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
3096
3097
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
3098
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
3099
0
        if (affected_by_floating_point_precision)
3100
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
3101
3102
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
3103
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
3104
0
    }
3105
3106
    // Step 0 or 1: Calculate the actual ranges of visible elements.
3107
0
    const int already_submitted = clipper->DisplayEnd;
3108
0
    if (calc_clipping)
3109
0
    {
3110
0
        if (g.LogEnabled)
3111
0
        {
3112
            // If logging is active, do not perform any clipping
3113
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
3114
0
        }
3115
0
        else
3116
0
        {
3117
            // Add range selected to be included for navigation
3118
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3119
0
            if (is_nav_request)
3120
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
3121
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3122
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3123
3124
            // Add focused/active item
3125
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3126
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3127
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3128
3129
            // Add visible range
3130
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3131
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3132
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
3133
0
        }
3134
3135
        // Convert position ranges to item index ranges
3136
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
3137
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3138
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3139
0
        for (ImGuiListClipperRange& range : data->Ranges)
3140
0
            if (range.PosToIndexConvert)
3141
0
            {
3142
0
                int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3143
0
                int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3144
0
                range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3145
0
                range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3146
0
                range.PosToIndexConvert = false;
3147
0
            }
3148
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3149
0
    }
3150
3151
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3152
0
    while (data->StepNo < data->Ranges.Size)
3153
0
    {
3154
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3155
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3156
0
        if (clipper->DisplayStart > already_submitted) //-V1051
3157
0
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
3158
0
        data->StepNo++;
3159
0
        if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3160
0
            continue;
3161
0
        return true;
3162
0
    }
3163
3164
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3165
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3166
0
    if (clipper->ItemsCount < INT_MAX)
3167
0
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
3168
3169
0
    return false;
3170
0
}
3171
3172
bool ImGuiListClipper::Step()
3173
0
{
3174
0
    ImGuiContext& g = *Ctx;
3175
0
    bool need_items_height = (ItemsHeight <= 0.0f);
3176
0
    bool ret = ImGuiListClipper_StepInternal(this);
3177
0
    if (ret && (DisplayStart == DisplayEnd))
3178
0
        ret = false;
3179
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3180
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3181
0
    if (need_items_height && ItemsHeight > 0.0f)
3182
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3183
0
    if (ret)
3184
0
    {
3185
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3186
0
    }
3187
0
    else
3188
0
    {
3189
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3190
0
        End();
3191
0
    }
3192
0
    return ret;
3193
0
}
3194
3195
//-----------------------------------------------------------------------------
3196
// [SECTION] STYLING
3197
//-----------------------------------------------------------------------------
3198
3199
ImGuiStyle& ImGui::GetStyle()
3200
136k
{
3201
136k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3202
136k
    return GImGui->Style;
3203
136k
}
3204
3205
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3206
1.00M
{
3207
1.00M
    ImGuiStyle& style = GImGui->Style;
3208
1.00M
    ImVec4 c = style.Colors[idx];
3209
1.00M
    c.w *= style.Alpha * alpha_mul;
3210
1.00M
    return ColorConvertFloat4ToU32(c);
3211
1.00M
}
3212
3213
ImU32 ImGui::GetColorU32(const ImVec4& col)
3214
0
{
3215
0
    ImGuiStyle& style = GImGui->Style;
3216
0
    ImVec4 c = col;
3217
0
    c.w *= style.Alpha;
3218
0
    return ColorConvertFloat4ToU32(c);
3219
0
}
3220
3221
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3222
0
{
3223
0
    ImGuiStyle& style = GImGui->Style;
3224
0
    return style.Colors[idx];
3225
0
}
3226
3227
ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3228
0
{
3229
0
    ImGuiStyle& style = GImGui->Style;
3230
0
    alpha_mul *= style.Alpha;
3231
0
    if (alpha_mul >= 1.0f)
3232
0
        return col;
3233
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3234
0
    a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3235
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3236
0
}
3237
3238
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3239
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3240
0
{
3241
0
    ImGuiContext& g = *GImGui;
3242
0
    ImGuiColorMod backup;
3243
0
    backup.Col = idx;
3244
0
    backup.BackupValue = g.Style.Colors[idx];
3245
0
    g.ColorStack.push_back(backup);
3246
0
    if (g.DebugFlashStyleColorIdx != idx)
3247
0
        g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3248
0
}
3249
3250
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3251
79.1k
{
3252
79.1k
    ImGuiContext& g = *GImGui;
3253
79.1k
    ImGuiColorMod backup;
3254
79.1k
    backup.Col = idx;
3255
79.1k
    backup.BackupValue = g.Style.Colors[idx];
3256
79.1k
    g.ColorStack.push_back(backup);
3257
79.1k
    if (g.DebugFlashStyleColorIdx != idx)
3258
79.1k
        g.Style.Colors[idx] = col;
3259
79.1k
}
3260
3261
void ImGui::PopStyleColor(int count)
3262
79.1k
{
3263
79.1k
    ImGuiContext& g = *GImGui;
3264
79.1k
    if (g.ColorStack.Size < count)
3265
0
    {
3266
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times!");
3267
0
        count = g.ColorStack.Size;
3268
0
    }
3269
158k
    while (count > 0)
3270
79.1k
    {
3271
79.1k
        ImGuiColorMod& backup = g.ColorStack.back();
3272
79.1k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3273
79.1k
        g.ColorStack.pop_back();
3274
79.1k
        count--;
3275
79.1k
    }
3276
79.1k
}
3277
3278
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3279
{
3280
    ImGuiCol_Text, ImGuiCol_TabHovered, ImGuiCol_Tab, ImGuiCol_TabSelected, ImGuiCol_TabSelectedOverline, ImGuiCol_TabDimmed, ImGuiCol_TabDimmedSelected, ImGuiCol_TabDimmedSelectedOverline,
3281
};
3282
3283
static const ImGuiDataVarInfo GStyleVarInfo[] =
3284
{
3285
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) },                     // ImGuiStyleVar_Alpha
3286
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) },             // ImGuiStyleVar_DisabledAlpha
3287
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowPadding) },             // ImGuiStyleVar_WindowPadding
3288
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowRounding) },            // ImGuiStyleVar_WindowRounding
3289
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) },          // ImGuiStyleVar_WindowBorderSize
3290
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowMinSize) },             // ImGuiStyleVar_WindowMinSize
3291
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) },          // ImGuiStyleVar_WindowTitleAlign
3292
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildRounding) },             // ImGuiStyleVar_ChildRounding
3293
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) },           // ImGuiStyleVar_ChildBorderSize
3294
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupRounding) },             // ImGuiStyleVar_PopupRounding
3295
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) },           // ImGuiStyleVar_PopupBorderSize
3296
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, FramePadding) },              // ImGuiStyleVar_FramePadding
3297
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameRounding) },             // ImGuiStyleVar_FrameRounding
3298
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) },           // ImGuiStyleVar_FrameBorderSize
3299
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemSpacing) },               // ImGuiStyleVar_ItemSpacing
3300
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) },          // ImGuiStyleVar_ItemInnerSpacing
3301
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, IndentSpacing) },             // ImGuiStyleVar_IndentSpacing
3302
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, CellPadding) },               // ImGuiStyleVar_CellPadding
3303
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) },             // ImGuiStyleVar_ScrollbarSize
3304
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) },         // ImGuiStyleVar_ScrollbarRounding
3305
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabMinSize) },               // ImGuiStyleVar_GrabMinSize
3306
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabRounding) },              // ImGuiStyleVar_GrabRounding
3307
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) },               // ImGuiStyleVar_TabRounding
3308
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBorderSize) },             // ImGuiStyleVar_TabBorderSize
3309
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) },          // ImGuiStyleVar_TabBarBorderSize
3310
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)},    // ImGuiStyleVar_TableAngledHeadersAngle
3311
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign
3312
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) },           // ImGuiStyleVar_ButtonTextAlign
3313
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) },       // ImGuiStyleVar_SelectableTextAlign
3314
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)},    // ImGuiStyleVar_SeparatorTextBorderSize
3315
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) },        // ImGuiStyleVar_SeparatorTextAlign
3316
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) },      // ImGuiStyleVar_SeparatorTextPadding
3317
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) },      // ImGuiStyleVar_DockingSeparatorSize
3318
};
3319
3320
const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3321
158k
{
3322
158k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3323
158k
    IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3324
158k
    return &GStyleVarInfo[idx];
3325
158k
}
3326
3327
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3328
0
{
3329
0
    ImGuiContext& g = *GImGui;
3330
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3331
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3332
0
    {
3333
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3334
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3335
0
        *pvar = val;
3336
0
        return;
3337
0
    }
3338
0
    IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3339
0
}
3340
3341
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3342
79.1k
{
3343
79.1k
    ImGuiContext& g = *GImGui;
3344
79.1k
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3345
79.1k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3346
79.1k
    {
3347
79.1k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3348
79.1k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3349
79.1k
        *pvar = val;
3350
79.1k
        return;
3351
79.1k
    }
3352
0
    IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3353
0
}
3354
3355
void ImGui::PopStyleVar(int count)
3356
79.1k
{
3357
79.1k
    ImGuiContext& g = *GImGui;
3358
79.1k
    if (g.StyleVarStack.Size < count)
3359
0
    {
3360
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times!");
3361
0
        count = g.StyleVarStack.Size;
3362
0
    }
3363
158k
    while (count > 0)
3364
79.1k
    {
3365
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3366
79.1k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3367
79.1k
        const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3368
79.1k
        void* data = info->GetVarPtr(&g.Style);
3369
79.1k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3370
79.1k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3371
79.1k
        g.StyleVarStack.pop_back();
3372
79.1k
        count--;
3373
79.1k
    }
3374
79.1k
}
3375
3376
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3377
0
{
3378
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3379
0
    switch (idx)
3380
0
    {
3381
0
    case ImGuiCol_Text: return "Text";
3382
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3383
0
    case ImGuiCol_WindowBg: return "WindowBg";
3384
0
    case ImGuiCol_ChildBg: return "ChildBg";
3385
0
    case ImGuiCol_PopupBg: return "PopupBg";
3386
0
    case ImGuiCol_Border: return "Border";
3387
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3388
0
    case ImGuiCol_FrameBg: return "FrameBg";
3389
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3390
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3391
0
    case ImGuiCol_TitleBg: return "TitleBg";
3392
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3393
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3394
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3395
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3396
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3397
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3398
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3399
0
    case ImGuiCol_CheckMark: return "CheckMark";
3400
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3401
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3402
0
    case ImGuiCol_Button: return "Button";
3403
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3404
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3405
0
    case ImGuiCol_Header: return "Header";
3406
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3407
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3408
0
    case ImGuiCol_Separator: return "Separator";
3409
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3410
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3411
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3412
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3413
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3414
0
    case ImGuiCol_TabHovered: return "TabHovered";
3415
0
    case ImGuiCol_Tab: return "Tab";
3416
0
    case ImGuiCol_TabSelected: return "TabSelected";
3417
0
    case ImGuiCol_TabSelectedOverline: return "TabSelectedOverline";
3418
0
    case ImGuiCol_TabDimmed: return "TabDimmed";
3419
0
    case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected";
3420
0
    case ImGuiCol_TabDimmedSelectedOverline: return "TabDimmedSelectedOverline";
3421
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3422
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3423
0
    case ImGuiCol_PlotLines: return "PlotLines";
3424
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3425
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3426
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3427
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3428
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3429
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3430
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3431
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3432
0
    case ImGuiCol_TextLink: return "TextLink";
3433
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3434
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3435
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3436
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3437
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3438
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3439
0
    }
3440
0
    IM_ASSERT(0);
3441
0
    return "Unknown";
3442
0
}
3443
3444
3445
//-----------------------------------------------------------------------------
3446
// [SECTION] RENDER HELPERS
3447
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3448
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3449
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3450
//-----------------------------------------------------------------------------
3451
3452
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3453
316k
{
3454
316k
    const char* text_display_end = text;
3455
316k
    if (!text_end)
3456
316k
        text_end = (const char*)-1;
3457
3458
2.84M
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3459
2.53M
        text_display_end++;
3460
316k
    return text_display_end;
3461
316k
}
3462
3463
// Internal ImGui functions to render text
3464
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3465
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3466
0
{
3467
0
    ImGuiContext& g = *GImGui;
3468
0
    ImGuiWindow* window = g.CurrentWindow;
3469
3470
    // Hide anything after a '##' string
3471
0
    const char* text_display_end;
3472
0
    if (hide_text_after_hash)
3473
0
    {
3474
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3475
0
    }
3476
0
    else
3477
0
    {
3478
0
        if (!text_end)
3479
0
            text_end = text + strlen(text); // FIXME-OPT
3480
0
        text_display_end = text_end;
3481
0
    }
3482
3483
0
    if (text != text_display_end)
3484
0
    {
3485
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3486
0
        if (g.LogEnabled)
3487
0
            LogRenderedText(&pos, text, text_display_end);
3488
0
    }
3489
0
}
3490
3491
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3492
0
{
3493
0
    ImGuiContext& g = *GImGui;
3494
0
    ImGuiWindow* window = g.CurrentWindow;
3495
3496
0
    if (!text_end)
3497
0
        text_end = text + strlen(text); // FIXME-OPT
3498
3499
0
    if (text != text_end)
3500
0
    {
3501
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3502
0
        if (g.LogEnabled)
3503
0
            LogRenderedText(&pos, text, text_end);
3504
0
    }
3505
0
}
3506
3507
// Default clip_rect uses (pos_min,pos_max)
3508
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3509
// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3510
// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3511
// better advantage of the render function taking size into account for coarse clipping.
3512
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3513
158k
{
3514
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3515
158k
    ImVec2 pos = pos_min;
3516
158k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3517
3518
158k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3519
158k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3520
158k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3521
158k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3522
158k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3523
3524
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3525
158k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3526
158k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3527
3528
    // Render
3529
158k
    if (need_clipping)
3530
79.1k
    {
3531
79.1k
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3532
79.1k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3533
79.1k
    }
3534
79.1k
    else
3535
79.1k
    {
3536
79.1k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3537
79.1k
    }
3538
158k
}
3539
3540
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3541
158k
{
3542
    // Hide anything after a '##' string
3543
158k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3544
158k
    const int text_len = (int)(text_display_end - text);
3545
158k
    if (text_len == 0)
3546
0
        return;
3547
3548
158k
    ImGuiContext& g = *GImGui;
3549
158k
    ImGuiWindow* window = g.CurrentWindow;
3550
158k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3551
158k
    if (g.LogEnabled)
3552
0
        LogRenderedText(&pos_min, text, text_display_end);
3553
158k
}
3554
3555
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3556
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3557
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3558
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3559
0
{
3560
0
    ImGuiContext& g = *GImGui;
3561
0
    if (text_end_full == NULL)
3562
0
        text_end_full = FindRenderedTextEnd(text);
3563
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3564
3565
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3566
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3567
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3568
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3569
0
    if (text_size.x > pos_max.x - pos_min.x)
3570
0
    {
3571
        // Hello wo...
3572
        // |       |   |
3573
        // min   max   ellipsis_max
3574
        //          <-> this is generally some padding value
3575
3576
0
        const ImFont* font = draw_list->_Data->Font;
3577
0
        const float font_size = draw_list->_Data->FontSize;
3578
0
        const float font_scale = draw_list->_Data->FontScale;
3579
0
        const char* text_end_ellipsis = NULL;
3580
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3581
3582
        // We can now claim the space between pos_max.x and ellipsis_max.x
3583
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3584
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3585
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3586
0
        {
3587
            // Always display at least 1 character if there's no room for character + ellipsis
3588
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3589
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3590
0
        }
3591
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3592
0
        {
3593
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3594
0
            text_end_ellipsis--;
3595
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3596
0
        }
3597
3598
        // Render text, render ellipsis
3599
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3600
0
        ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3601
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3602
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3603
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3604
0
    }
3605
0
    else
3606
0
    {
3607
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3608
0
    }
3609
3610
0
    if (g.LogEnabled)
3611
0
        LogRenderedText(&pos_min, text, text_end_full);
3612
0
}
3613
3614
// Render a rectangle shaped with optional rounding and borders
3615
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3616
67.6k
{
3617
67.6k
    ImGuiContext& g = *GImGui;
3618
67.6k
    ImGuiWindow* window = g.CurrentWindow;
3619
67.6k
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3620
67.6k
    const float border_size = g.Style.FrameBorderSize;
3621
67.6k
    if (border && border_size > 0.0f)
3622
67.6k
    {
3623
67.6k
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3624
67.6k
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3625
67.6k
    }
3626
67.6k
}
3627
3628
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3629
0
{
3630
0
    ImGuiContext& g = *GImGui;
3631
0
    ImGuiWindow* window = g.CurrentWindow;
3632
0
    const float border_size = g.Style.FrameBorderSize;
3633
0
    if (border_size > 0.0f)
3634
0
    {
3635
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3636
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3637
0
    }
3638
0
}
3639
3640
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3641
13.1k
{
3642
13.1k
    ImGuiContext& g = *GImGui;
3643
13.1k
    if (id != g.NavId)
3644
8.56k
        return;
3645
4.63k
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3646
372
        return;
3647
4.25k
    ImGuiWindow* window = g.CurrentWindow;
3648
4.25k
    if (window->DC.NavHideHighlightOneFrame)
3649
0
        return;
3650
3651
4.25k
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3652
4.25k
    ImRect display_rect = bb;
3653
4.25k
    display_rect.ClipWith(window->ClipRect);
3654
4.25k
    const float thickness = 2.0f;
3655
4.25k
    if (flags & ImGuiNavHighlightFlags_Compact)
3656
4.10k
    {
3657
4.10k
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3658
4.10k
    }
3659
159
    else
3660
159
    {
3661
159
        const float distance = 3.0f + thickness * 0.5f;
3662
159
        display_rect.Expand(ImVec2(distance, distance));
3663
159
        bool fully_visible = window->ClipRect.Contains(display_rect);
3664
159
        if (!fully_visible)
3665
0
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3666
159
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3667
159
        if (!fully_visible)
3668
0
            window->DrawList->PopClipRect();
3669
159
    }
3670
4.25k
}
3671
3672
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3673
0
{
3674
0
    ImGuiContext& g = *GImGui;
3675
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3676
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3677
0
    for (ImGuiViewportP* viewport : g.Viewports)
3678
0
    {
3679
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3680
0
        ImVec2 offset, size, uv[4];
3681
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3682
0
            continue;
3683
0
        const ImVec2 pos = base_pos - offset;
3684
0
        const float scale = base_scale * viewport->DpiScale;
3685
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3686
0
            continue;
3687
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3688
0
        ImTextureID tex_id = font_atlas->TexID;
3689
0
        draw_list->PushTextureID(tex_id);
3690
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3691
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3692
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3693
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3694
0
        draw_list->PopTextureID();
3695
0
    }
3696
0
}
3697
3698
//-----------------------------------------------------------------------------
3699
// [SECTION] INITIALIZATION, SHUTDOWN
3700
//-----------------------------------------------------------------------------
3701
3702
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3703
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3704
ImGuiContext* ImGui::GetCurrentContext()
3705
1
{
3706
1
    return GImGui;
3707
1
}
3708
3709
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3710
1
{
3711
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3712
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3713
#else
3714
1
    GImGui = ctx;
3715
1
#endif
3716
1
}
3717
3718
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3719
0
{
3720
0
    GImAllocatorAllocFunc = alloc_func;
3721
0
    GImAllocatorFreeFunc = free_func;
3722
0
    GImAllocatorUserData = user_data;
3723
0
}
3724
3725
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3726
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3727
0
{
3728
0
    *p_alloc_func = GImAllocatorAllocFunc;
3729
0
    *p_free_func = GImAllocatorFreeFunc;
3730
0
    *p_user_data = GImAllocatorUserData;
3731
0
}
3732
3733
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3734
1
{
3735
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3736
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3737
1
    SetCurrentContext(ctx);
3738
1
    Initialize();
3739
1
    if (prev_ctx != NULL)
3740
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3741
1
    return ctx;
3742
1
}
3743
3744
void ImGui::DestroyContext(ImGuiContext* ctx)
3745
0
{
3746
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3747
0
    if (ctx == NULL) //-V1051
3748
0
        ctx = prev_ctx;
3749
0
    SetCurrentContext(ctx);
3750
0
    Shutdown();
3751
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3752
0
    IM_DELETE(ctx);
3753
0
}
3754
3755
// IMPORTANT: ###xxx suffixes must be same in ALL languages to allow for automation.
3756
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3757
{
3758
    { ImGuiLocKey_VersionStr,           "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3759
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3760
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3761
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3762
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3763
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3764
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3765
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3766
    { ImGuiLocKey_CopyLink,             "Copy Link###CopyLink"                  },
3767
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3768
    { ImGuiLocKey_DockingHoldShiftToDock,       "Hold SHIFT to enable Docking window."  },
3769
    { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node."    },
3770
};
3771
3772
void ImGui::Initialize()
3773
1
{
3774
1
    ImGuiContext& g = *GImGui;
3775
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3776
3777
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3778
1
    {
3779
1
        ImGuiSettingsHandler ini_handler;
3780
1
        ini_handler.TypeName = "Window";
3781
1
        ini_handler.TypeHash = ImHashStr("Window");
3782
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3783
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3784
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3785
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3786
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3787
1
        AddSettingsHandler(&ini_handler);
3788
1
    }
3789
1
    TableSettingsAddSettingsHandler();
3790
3791
    // Setup default localization table
3792
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3793
3794
    // Setup default platform clipboard/IME handlers.
3795
1
    g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;    // Platform dependent default implementations
3796
1
    g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3797
1
    g.IO.ClipboardUserData = (void*)&g;                          // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3798
1
    g.IO.PlatformOpenInShellFn = PlatformOpenInShellFn_DefaultImpl;
3799
1
    g.IO.PlatformSetImeDataFn = PlatformSetImeDataFn_DefaultImpl;
3800
3801
    // Create default viewport
3802
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3803
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3804
1
    viewport->Idx = 0;
3805
1
    viewport->PlatformWindowCreated = true;
3806
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3807
1
    g.Viewports.push_back(viewport);
3808
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3809
1
    g.ViewportCreatedCount++;
3810
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3811
3812
    // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
3813
155
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
3814
154
        if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
3815
154
            || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
3816
154
            || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
3817
154
            || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
3818
64
            g.KeysMayBeCharInput.SetBit(key);
3819
3820
1
#ifdef IMGUI_HAS_DOCK
3821
    // Initialize Docking
3822
1
    DockContextInitialize(&g);
3823
1
#endif
3824
3825
1
    g.Initialized = true;
3826
1
}
3827
3828
// This function is merely here to free heap allocations.
3829
void ImGui::Shutdown()
3830
0
{
3831
0
    ImGuiContext& g = *GImGui;
3832
0
    IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
3833
0
    IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
3834
3835
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3836
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3837
0
    {
3838
0
        g.IO.Fonts->Locked = false;
3839
0
        IM_DELETE(g.IO.Fonts);
3840
0
    }
3841
0
    g.IO.Fonts = NULL;
3842
0
    g.DrawListSharedData.TempBuffer.clear();
3843
3844
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3845
0
    if (!g.Initialized)
3846
0
        return;
3847
3848
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3849
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3850
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3851
3852
    // Destroy platform windows
3853
0
    DestroyPlatformWindows();
3854
3855
    // Shutdown extensions
3856
0
    DockContextShutdown(&g);
3857
3858
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3859
3860
    // Clear everything else
3861
0
    g.Windows.clear_delete();
3862
0
    g.WindowsFocusOrder.clear();
3863
0
    g.WindowsTempSortBuffer.clear();
3864
0
    g.CurrentWindow = NULL;
3865
0
    g.CurrentWindowStack.clear();
3866
0
    g.WindowsById.Clear();
3867
0
    g.NavWindow = NULL;
3868
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3869
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3870
0
    g.MovingWindow = NULL;
3871
3872
0
    g.KeysRoutingTable.Clear();
3873
3874
0
    g.ColorStack.clear();
3875
0
    g.StyleVarStack.clear();
3876
0
    g.FontStack.clear();
3877
0
    g.OpenPopupStack.clear();
3878
0
    g.BeginPopupStack.clear();
3879
0
    g.NavTreeNodeStack.clear();
3880
3881
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3882
0
    g.Viewports.clear_delete();
3883
3884
0
    g.TabBars.Clear();
3885
0
    g.CurrentTabBarStack.clear();
3886
0
    g.ShrinkWidthBuffer.clear();
3887
3888
0
    g.ClipperTempData.clear_destruct();
3889
3890
0
    g.Tables.Clear();
3891
0
    g.TablesTempData.clear_destruct();
3892
0
    g.DrawChannelsTempMergeBuffer.clear();
3893
3894
0
    g.ClipboardHandlerData.clear();
3895
0
    g.MenusIdSubmittedThisFrame.clear();
3896
0
    g.InputTextState.ClearFreeMemory();
3897
0
    g.InputTextDeactivatedState.ClearFreeMemory();
3898
3899
0
    g.SettingsWindows.clear();
3900
0
    g.SettingsHandlers.clear();
3901
3902
0
    if (g.LogFile)
3903
0
    {
3904
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3905
0
        if (g.LogFile != stdout)
3906
0
#endif
3907
0
            ImFileClose(g.LogFile);
3908
0
        g.LogFile = NULL;
3909
0
    }
3910
0
    g.LogBuffer.clear();
3911
0
    g.DebugLogBuf.clear();
3912
0
    g.DebugLogIndex.clear();
3913
3914
0
    g.Initialized = false;
3915
0
}
3916
3917
// No specific ordering/dependency support, will see as needed
3918
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3919
0
{
3920
0
    ImGuiContext& g = *ctx;
3921
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3922
0
    g.Hooks.push_back(*hook);
3923
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3924
0
    return g.HookIdNext;
3925
0
}
3926
3927
// Deferred removal, avoiding issue with changing vector while iterating it
3928
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3929
0
{
3930
0
    ImGuiContext& g = *ctx;
3931
0
    IM_ASSERT(hook_id != 0);
3932
0
    for (ImGuiContextHook& hook : g.Hooks)
3933
0
        if (hook.HookId == hook_id)
3934
0
            hook.Type = ImGuiContextHookType_PendingRemoval_;
3935
0
}
3936
3937
// Call context hooks (used by e.g. test engine)
3938
// We assume a small number of hooks so all stored in same array
3939
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3940
474k
{
3941
474k
    ImGuiContext& g = *ctx;
3942
474k
    for (ImGuiContextHook& hook : g.Hooks)
3943
0
        if (hook.Type == hook_type)
3944
0
            hook.Callback(&g, &hook);
3945
474k
}
3946
3947
3948
//-----------------------------------------------------------------------------
3949
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3950
//-----------------------------------------------------------------------------
3951
3952
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3953
ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3954
3
{
3955
3
    memset(this, 0, sizeof(*this));
3956
3
    Ctx = ctx;
3957
3
    Name = ImStrdup(name);
3958
3
    NameBufLen = (int)strlen(name) + 1;
3959
3
    ID = ImHashStr(name);
3960
3
    IDStack.push_back(ID);
3961
3
    ViewportAllowPlatformMonitorExtend = -1;
3962
3
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3963
3
    MoveId = GetID("#MOVE");
3964
3
    TabId = GetID("#TAB");
3965
3
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3966
3
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3967
3
    AutoFitFramesX = AutoFitFramesY = -1;
3968
3
    AutoPosLastDirection = ImGuiDir_None;
3969
3
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3970
3
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3971
3
    LastFrameActive = -1;
3972
3
    LastFrameJustFocused = -1;
3973
3
    LastTimeActive = -1.0f;
3974
3
    FontWindowScale = FontDpiScale = 1.0f;
3975
3
    SettingsOffset = -1;
3976
3
    DockOrder = -1;
3977
3
    DrawList = &DrawListInst;
3978
3
    DrawList->_Data = &Ctx->DrawListSharedData;
3979
3
    DrawList->_OwnerName = Name;
3980
3
    NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
3981
3
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3982
3
}
3983
3984
ImGuiWindow::~ImGuiWindow()
3985
0
{
3986
0
    IM_ASSERT(DrawList == &DrawListInst);
3987
0
    IM_DELETE(Name);
3988
0
    ColumnsStorage.clear_destruct();
3989
0
}
3990
3991
static void SetCurrentWindow(ImGuiWindow* window)
3992
339k
{
3993
339k
    ImGuiContext& g = *GImGui;
3994
339k
    g.CurrentWindow = window;
3995
339k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3996
339k
    if (window)
3997
260k
    {
3998
260k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3999
260k
        g.FontScale = g.FontSize / g.Font->FontSize;
4000
260k
        ImGui::NavUpdateCurrentWindowIsScrollPushableX();
4001
260k
    }
4002
339k
}
4003
4004
void ImGui::GcCompactTransientMiscBuffers()
4005
0
{
4006
0
    ImGuiContext& g = *GImGui;
4007
0
    g.ItemFlagsStack.clear();
4008
0
    g.GroupStack.clear();
4009
0
    TableGcCompactSettings();
4010
0
}
4011
4012
// Free up/compact internal window buffers, we can use this when a window becomes unused.
4013
// Not freed:
4014
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
4015
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
4016
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
4017
1
{
4018
1
    window->MemoryCompacted = true;
4019
1
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
4020
1
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
4021
1
    window->IDStack.clear();
4022
1
    window->DrawList->_ClearFreeMemory();
4023
1
    window->DC.ChildWindows.clear();
4024
1
    window->DC.ItemWidthStack.clear();
4025
1
    window->DC.TextWrapPosStack.clear();
4026
1
}
4027
4028
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
4029
0
{
4030
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
4031
    // The other buffers tends to amortize much faster.
4032
0
    window->MemoryCompacted = false;
4033
0
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
4034
0
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
4035
0
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
4036
0
}
4037
4038
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
4039
100
{
4040
100
    ImGuiContext& g = *GImGui;
4041
4042
    // Clear previous active id
4043
100
    if (g.ActiveId != 0)
4044
17
    {
4045
        // While most behaved code would make an effort to not steal active id during window move/drag operations,
4046
        // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
4047
        // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
4048
17
        if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
4049
0
        {
4050
0
            IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
4051
0
            g.MovingWindow = NULL;
4052
0
        }
4053
4054
        // This could be written in a more general way (e.g associate a hook to ActiveId),
4055
        // but since this is currently quite an exception we'll leave it as is.
4056
        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
4057
17
        if (g.InputTextState.ID == g.ActiveId)
4058
0
            InputTextDeactivateHook(g.ActiveId);
4059
17
    }
4060
4061
    // Set active id
4062
100
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
4063
100
    if (g.ActiveIdIsJustActivated)
4064
33
    {
4065
33
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
4066
33
        g.ActiveIdTimer = 0.0f;
4067
33
        g.ActiveIdHasBeenPressedBefore = false;
4068
33
        g.ActiveIdHasBeenEditedBefore = false;
4069
33
        g.ActiveIdMouseButton = -1;
4070
33
        if (id != 0)
4071
17
        {
4072
17
            g.LastActiveId = id;
4073
17
            g.LastActiveIdTimer = 0.0f;
4074
17
        }
4075
33
    }
4076
100
    g.ActiveId = id;
4077
100
    g.ActiveIdAllowOverlap = false;
4078
100
    g.ActiveIdNoClearOnFocusLoss = false;
4079
100
    g.ActiveIdWindow = window;
4080
100
    g.ActiveIdHasBeenEditedThisFrame = false;
4081
100
    g.ActiveIdFromShortcut = false;
4082
100
    if (id)
4083
17
    {
4084
17
        g.ActiveIdIsAlive = id;
4085
17
        g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4086
17
        IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4087
17
    }
4088
4089
    // Clear declaration of inputs claimed by the widget
4090
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4091
100
    g.ActiveIdUsingNavDirMask = 0x00;
4092
100
    g.ActiveIdUsingAllKeyboardKeys = false;
4093
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4094
    g.ActiveIdUsingNavInputMask = 0x00;
4095
#endif
4096
100
}
4097
4098
void ImGui::ClearActiveID()
4099
83
{
4100
83
    SetActiveID(0, NULL); // g.ActiveId = 0;
4101
83
}
4102
4103
void ImGui::SetHoveredID(ImGuiID id)
4104
33
{
4105
33
    ImGuiContext& g = *GImGui;
4106
33
    g.HoveredId = id;
4107
33
    g.HoveredIdAllowOverlap = false;
4108
33
    if (id != 0 && g.HoveredIdPreviousFrame != id)
4109
8
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4110
33
}
4111
4112
ImGuiID ImGui::GetHoveredID()
4113
0
{
4114
0
    ImGuiContext& g = *GImGui;
4115
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4116
0
}
4117
4118
void ImGui::MarkItemEdited(ImGuiID id)
4119
0
{
4120
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
4121
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
4122
0
    ImGuiContext& g = *GImGui;
4123
0
    if (g.LockMarkEdited > 0)
4124
0
        return;
4125
0
    if (g.ActiveId == id || g.ActiveId == 0)
4126
0
    {
4127
0
        g.ActiveIdHasBeenEditedThisFrame = true;
4128
0
        g.ActiveIdHasBeenEditedBefore = true;
4129
0
    }
4130
4131
    // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4132
    // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4133
0
    IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id);
4134
4135
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4136
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4137
0
}
4138
4139
bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4140
36
{
4141
    // An active popup disable hovering on other windows (apart from its own children)
4142
    // FIXME-OPT: This could be cached/stored within the window.
4143
36
    ImGuiContext& g = *GImGui;
4144
36
    if (g.NavWindow)
4145
1
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4146
1
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4147
0
            {
4148
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4149
                // NB: The 'else' is important because Modal windows are also Popups.
4150
0
                bool want_inhibit = false;
4151
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4152
0
                    want_inhibit = true;
4153
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4154
0
                    want_inhibit = true;
4155
4156
                // Inhibit hover unless the window is within the stack of our modal/popup
4157
0
                if (want_inhibit)
4158
0
                    if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4159
0
                        return false;
4160
0
            }
4161
4162
    // Filter by viewport
4163
36
    if (window->Viewport != g.MouseViewport)
4164
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4165
0
            return false;
4166
4167
36
    return true;
4168
36
}
4169
4170
static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4171
0
{
4172
0
    ImGuiContext& g = *GImGui;
4173
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4174
0
        return g.Style.HoverDelayNormal;
4175
0
    if (flags & ImGuiHoveredFlags_DelayShort)
4176
0
        return g.Style.HoverDelayShort;
4177
0
    return 0.0f;
4178
0
}
4179
4180
static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4181
0
{
4182
    // Allow instance flags to override shared flags
4183
0
    if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4184
0
        shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4185
0
    return user_flags | shared_flags;
4186
0
}
4187
4188
// This is roughly matching the behavior of internal-facing ItemHoverable()
4189
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4190
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4191
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4192
0
{
4193
0
    ImGuiContext& g = *GImGui;
4194
0
    ImGuiWindow* window = g.CurrentWindow;
4195
0
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4196
4197
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4198
0
    {
4199
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4200
0
            return false;
4201
0
        if (!IsItemFocused())
4202
0
            return false;
4203
4204
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4205
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4206
0
    }
4207
0
    else
4208
0
    {
4209
        // Test for bounding box overlap, as updated as ItemAdd()
4210
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4211
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4212
0
            return false;
4213
4214
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4215
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4216
4217
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
4218
4219
        // Done with rectangle culling so we can perform heavier checks now
4220
        // Test if we are hovering the right window (our window could be behind another window)
4221
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4222
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4223
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4224
        // the test that has been running for a long while.
4225
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4226
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4227
0
                return false;
4228
4229
        // Test if another item is active (e.g. being dragged)
4230
0
        const ImGuiID id = g.LastItemData.ID;
4231
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4232
0
            if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4233
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4234
0
                    return false;
4235
4236
        // Test if interactions on this window are blocked by an active popup or modal.
4237
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4238
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4239
0
            return false;
4240
4241
        // Test if the item is disabled
4242
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4243
0
            return false;
4244
4245
        // Special handling for calling after Begin() which represent the title bar or tab.
4246
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4247
        // will never be overwritten so we need to detect the case.
4248
0
        if (id == window->MoveId && window->WriteAccessed)
4249
0
            return false;
4250
4251
        // Test if using AllowOverlap and overlapped
4252
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4253
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4254
0
                if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4255
0
                    return false;
4256
0
    }
4257
4258
    // Handle hover delay
4259
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4260
0
    const float delay = CalcDelayFromHoveredFlags(flags);
4261
0
    if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4262
0
    {
4263
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4264
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4265
0
            g.HoverItemDelayTimer = 0.0f;
4266
0
        g.HoverItemDelayId = hover_delay_id;
4267
4268
        // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4269
        // but once unlocked on a given item we also moving.
4270
        //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); }
4271
0
        if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4272
0
            return false;
4273
4274
0
        if (g.HoverItemDelayTimer < delay)
4275
0
            return false;
4276
0
    }
4277
4278
0
    return true;
4279
0
}
4280
4281
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4282
// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4283
// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4284
// If you used this in your legacy/custom widgets code:
4285
// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4286
// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4287
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4288
234k
{
4289
234k
    ImGuiContext& g = *GImGui;
4290
234k
    ImGuiWindow* window = g.CurrentWindow;
4291
234k
    if (g.HoveredWindow != window)
4292
232k
        return false;
4293
2.28k
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4294
2.25k
        return false;
4295
4296
33
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4297
0
        return false;
4298
33
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4299
0
        if (!g.ActiveIdFromShortcut)
4300
0
            return false;
4301
4302
    // Done with rectangle culling so we can perform heavier checks now.
4303
33
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4304
0
    {
4305
0
        g.HoveredIdIsDisabled = true;
4306
0
        return false;
4307
0
    }
4308
4309
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4310
    // hover test in widgets code. We could also decide to split this function is two.
4311
33
    if (id != 0)
4312
33
    {
4313
        // Drag source doesn't report as hovered
4314
33
        if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4315
0
            return false;
4316
4317
33
        SetHoveredID(id);
4318
4319
        // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4320
        // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4321
33
        if (item_flags & ImGuiItemFlags_AllowOverlap)
4322
0
        {
4323
0
            g.HoveredIdAllowOverlap = true;
4324
0
            if (g.HoveredIdPreviousFrame != id)
4325
0
                return false;
4326
0
        }
4327
4328
        // Display shortcut (only works with mouse)
4329
        // (ImGuiItemStatusFlags_HasShortcut in LastItemData denotes we want a tooltip)
4330
33
        if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut))
4331
0
            if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal))
4332
0
                SetTooltip("%s", GetKeyChordName(g.LastItemData.Shortcut));
4333
33
    }
4334
4335
    // When disabled we'll return false but still set HoveredId
4336
33
    if (item_flags & ImGuiItemFlags_Disabled)
4337
0
    {
4338
        // Release active id if turning disabled
4339
0
        if (g.ActiveId == id && id != 0)
4340
0
            ClearActiveID();
4341
0
        g.HoveredIdIsDisabled = true;
4342
0
        return false;
4343
0
    }
4344
4345
33
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4346
33
    if (id != 0)
4347
33
    {
4348
        // [DEBUG] Item Picker tool!
4349
        // We perform the check here because reaching is path is rare (1~ time a frame),
4350
        // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
4351
        // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
4352
33
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4353
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4354
33
        if (g.DebugItemPickerBreakId == id)
4355
0
            IM_DEBUG_BREAK();
4356
33
    }
4357
33
#endif
4358
4359
33
    if (g.NavDisableMouseHover)
4360
0
        return false;
4361
4362
33
    return true;
4363
33
}
4364
4365
// FIXME: This is inlined/duplicated in ItemAdd()
4366
// FIXME: The id != 0 path is not used by our codebase, may get rid of it?
4367
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4368
0
{
4369
0
    ImGuiContext& g = *GImGui;
4370
0
    ImGuiWindow* window = g.CurrentWindow;
4371
0
    if (!bb.Overlaps(window->ClipRect))
4372
0
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
4373
0
            if (!g.ItemUnclipByLog)
4374
0
                return true;
4375
0
    return false;
4376
0
}
4377
4378
// This is also inlined in ItemAdd()
4379
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4380
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4381
169k
{
4382
169k
    ImGuiContext& g = *GImGui;
4383
169k
    g.LastItemData.ID = item_id;
4384
169k
    g.LastItemData.InFlags = in_flags;
4385
169k
    g.LastItemData.StatusFlags = item_flags;
4386
169k
    g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4387
169k
}
4388
4389
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4390
0
{
4391
0
    if (wrap_pos_x < 0.0f)
4392
0
        return 0.0f;
4393
4394
0
    ImGuiContext& g = *GImGui;
4395
0
    ImGuiWindow* window = g.CurrentWindow;
4396
0
    if (wrap_pos_x == 0.0f)
4397
0
    {
4398
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4399
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4400
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4401
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4402
        //else
4403
0
        wrap_pos_x = window->WorkRect.Max.x;
4404
0
    }
4405
0
    else if (wrap_pos_x > 0.0f)
4406
0
    {
4407
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4408
0
    }
4409
4410
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4411
0
}
4412
4413
// IM_ALLOC() == ImGui::MemAlloc()
4414
void* ImGui::MemAlloc(size_t size)
4415
1.22k
{
4416
1.22k
    void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4417
1.22k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4418
1.22k
    if (ImGuiContext* ctx = GImGui)
4419
1.21k
        DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
4420
1.22k
#endif
4421
1.22k
    return ptr;
4422
1.22k
}
4423
4424
// IM_FREE() == ImGui::MemFree()
4425
void ImGui::MemFree(void* ptr)
4426
1.17k
{
4427
1.17k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4428
1.17k
    if (ptr != NULL)
4429
1.16k
        if (ImGuiContext* ctx = GImGui)
4430
1.16k
            DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
4431
1.17k
#endif
4432
1.17k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4433
1.17k
}
4434
4435
// We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames"
4436
void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4437
2.38k
{
4438
2.38k
    ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4439
2.38k
    IM_UNUSED(ptr);
4440
2.38k
    if (entry->FrameCount != frame_count)
4441
35
    {
4442
35
        info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4443
35
        entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4444
35
        entry->FrameCount = frame_count;
4445
35
        entry->AllocCount = entry->FreeCount = 0;
4446
35
    }
4447
2.38k
    if (size != (size_t)-1)
4448
1.21k
    {
4449
1.21k
        entry->AllocCount++;
4450
1.21k
        info->TotalAllocCount++;
4451
        //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
4452
1.21k
    }
4453
1.16k
    else
4454
1.16k
    {
4455
1.16k
        entry->FreeCount++;
4456
1.16k
        info->TotalFreeCount++;
4457
        //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4458
1.16k
    }
4459
2.38k
}
4460
4461
const char* ImGui::GetClipboardText()
4462
0
{
4463
0
    ImGuiContext& g = *GImGui;
4464
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4465
0
}
4466
4467
void ImGui::SetClipboardText(const char* text)
4468
0
{
4469
0
    ImGuiContext& g = *GImGui;
4470
0
    if (g.IO.SetClipboardTextFn)
4471
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4472
0
}
4473
4474
const char* ImGui::GetVersion()
4475
0
{
4476
0
    return IMGUI_VERSION;
4477
0
}
4478
4479
ImGuiIO& ImGui::GetIO()
4480
223k
{
4481
223k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4482
223k
    return GImGui->IO;
4483
223k
}
4484
4485
ImGuiPlatformIO& ImGui::GetPlatformIO()
4486
0
{
4487
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext()?");
4488
0
    return GImGui->PlatformIO;
4489
0
}
4490
4491
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4492
ImDrawData* ImGui::GetDrawData()
4493
79.1k
{
4494
79.1k
    ImGuiContext& g = *GImGui;
4495
79.1k
    ImGuiViewportP* viewport = g.Viewports[0];
4496
79.1k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4497
79.1k
}
4498
4499
double ImGui::GetTime()
4500
3
{
4501
3
    return GImGui->Time;
4502
3
}
4503
4504
int ImGui::GetFrameCount()
4505
0
{
4506
0
    return GImGui->FrameCount;
4507
0
}
4508
4509
static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4510
0
{
4511
    // Create the draw list on demand, because they are not frequently used for all viewports
4512
0
    ImGuiContext& g = *GImGui;
4513
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4514
0
    ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4515
0
    if (draw_list == NULL)
4516
0
    {
4517
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4518
0
        draw_list->_OwnerName = drawlist_name;
4519
0
        viewport->BgFgDrawLists[drawlist_no] = draw_list;
4520
0
    }
4521
4522
    // Our ImDrawList system requires that there is always a command
4523
0
    if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4524
0
    {
4525
0
        draw_list->_ResetForNewFrame();
4526
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4527
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4528
0
        viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4529
0
    }
4530
0
    return draw_list;
4531
0
}
4532
4533
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4534
0
{
4535
0
    if (viewport == NULL)
4536
0
        viewport = GImGui->CurrentWindow->Viewport;
4537
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4538
0
}
4539
4540
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4541
0
{
4542
0
    if (viewport == NULL)
4543
0
        viewport = GImGui->CurrentWindow->Viewport;
4544
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4545
0
}
4546
4547
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4548
0
{
4549
0
    return &GImGui->DrawListSharedData;
4550
0
}
4551
4552
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4553
4
{
4554
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4555
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4556
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4557
4
    ImGuiContext& g = *GImGui;
4558
4
    FocusWindow(window);
4559
4
    SetActiveID(window->MoveId, window);
4560
4
    g.NavDisableHighlight = true;
4561
4
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4562
4
    g.ActiveIdNoClearOnFocusLoss = true;
4563
4
    SetActiveIdUsingAllKeyboardKeys();
4564
4565
4
    bool can_move_window = true;
4566
4
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4567
0
        can_move_window = false;
4568
4
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4569
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4570
0
            can_move_window = false;
4571
4
    if (can_move_window)
4572
4
        g.MovingWindow = window;
4573
4
}
4574
4575
// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4576
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
4577
1
{
4578
1
    ImGuiContext& g = *GImGui;
4579
1
    bool can_undock_node = false;
4580
1
    if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
4581
0
    {
4582
        // Can undock if:
4583
        // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
4584
        // - part of a dockspace node hierarchy: so we can undock the last single visible node too (trivia: undocking from a fixed/central node will create a new node and copy windows)
4585
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4586
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4587
0
            can_undock_node = true;
4588
0
    }
4589
4590
1
    const bool clicked = IsMouseClicked(0);
4591
1
    const bool dragging = IsMouseDragging(0);
4592
1
    if (can_undock_node && dragging)
4593
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4594
1
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4595
1
        StartMouseMovingWindow(window);
4596
1
}
4597
4598
// Handle mouse moving window
4599
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4600
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4601
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4602
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4603
void ImGui::UpdateMouseMovingWindowNewFrame()
4604
79.1k
{
4605
79.1k
    ImGuiContext& g = *GImGui;
4606
79.1k
    if (g.MovingWindow != NULL)
4607
58
    {
4608
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4609
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4610
58
        KeepAliveID(g.ActiveId);
4611
58
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4612
58
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4613
4614
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4615
58
        const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
4616
58
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4617
54
        {
4618
54
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4619
54
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4620
8
            {
4621
8
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4622
8
                if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4623
0
                {
4624
0
                    moving_window->Viewport->Pos = pos;
4625
0
                    moving_window->Viewport->UpdateWorkRect();
4626
0
                }
4627
8
            }
4628
54
            FocusWindow(g.MovingWindow);
4629
54
        }
4630
4
        else
4631
4
        {
4632
4
            if (!window_disappared)
4633
4
            {
4634
                // Try to merge the window back into the main viewport.
4635
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4636
4
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4637
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4638
4639
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4640
4
                if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
4641
4
                    g.MouseViewport = moving_window->Viewport;
4642
4643
                // Clear the NoInput window flag set by the Viewport system
4644
4
                if (moving_window->Viewport)
4645
4
                    moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
4646
4
            }
4647
4648
4
            g.MovingWindow = NULL;
4649
4
            ClearActiveID();
4650
4
        }
4651
58
    }
4652
79.0k
    else
4653
79.0k
    {
4654
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4655
79.0k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4656
0
        {
4657
0
            KeepAliveID(g.ActiveId);
4658
0
            if (!g.IO.MouseDown[0])
4659
0
                ClearActiveID();
4660
0
        }
4661
79.0k
    }
4662
79.1k
}
4663
4664
// Initiate moving window when clicking on empty space or title bar.
4665
// Handle left-click and right-click focus.
4666
void ImGui::UpdateMouseMovingWindowEndFrame()
4667
79.1k
{
4668
79.1k
    ImGuiContext& g = *GImGui;
4669
79.1k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4670
99
        return;
4671
4672
    // Unless we just made a window/popup appear
4673
79.0k
    if (g.NavWindow && g.NavWindow->Appearing)
4674
1
        return;
4675
4676
    // Click on empty space to focus window and start moving
4677
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4678
79.0k
    if (g.IO.MouseClicked[0])
4679
2.18k
    {
4680
        // Handle the edge case of a popup being closed while clicking in its empty space.
4681
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4682
2.18k
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4683
2.18k
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4684
4685
2.18k
        if (root_window != NULL && !is_closed_popup)
4686
3
        {
4687
3
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4688
4689
            // Cancel moving if clicked outside of title bar
4690
3
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4691
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4692
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4693
0
                        g.MovingWindow = NULL;
4694
4695
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4696
3
            if (g.HoveredIdIsDisabled)
4697
0
                g.MovingWindow = NULL;
4698
3
        }
4699
2.18k
        else if (root_window == NULL && g.NavWindow != NULL)
4700
53
        {
4701
            // Clicking on void disable focus
4702
53
            FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4703
53
        }
4704
2.18k
    }
4705
4706
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4707
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4708
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4709
79.0k
    if (g.IO.MouseClicked[1])
4710
373
    {
4711
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4712
        // This is where we can trim the popup stack.
4713
373
        ImGuiWindow* modal = GetTopMostPopupModal();
4714
373
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4715
373
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4716
373
    }
4717
79.0k
}
4718
4719
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4720
// Need to keep in sync with SetWindowPos()
4721
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4722
0
{
4723
0
    window->Pos += delta;
4724
0
    window->ClipRect.Translate(delta);
4725
0
    window->OuterRectClipped.Translate(delta);
4726
0
    window->InnerRect.Translate(delta);
4727
0
    window->DC.CursorPos += delta;
4728
0
    window->DC.CursorStartPos += delta;
4729
0
    window->DC.CursorMaxPos += delta;
4730
0
    window->DC.IdealMaxPos += delta;
4731
0
}
4732
4733
static void ScaleWindow(ImGuiWindow* window, float scale)
4734
0
{
4735
0
    ImVec2 origin = window->Viewport->Pos;
4736
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4737
0
    window->Size = ImTrunc(window->Size * scale);
4738
0
    window->SizeFull = ImTrunc(window->SizeFull * scale);
4739
0
    window->ContentSize = ImTrunc(window->ContentSize * scale);
4740
0
}
4741
4742
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4743
248k
{
4744
248k
    return (window->Active) && (!window->Hidden);
4745
248k
}
4746
4747
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4748
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4749
79.1k
{
4750
79.1k
    ImGuiContext& g = *GImGui;
4751
79.1k
    ImGuiIO& io = g.IO;
4752
4753
    // FIXME-DPI: This storage was added on 2021/03/31 for test engine, but if we want to multiply WINDOWS_HOVER_PADDING
4754
    // by DpiScale, we need to make this window-agnostic anyhow, maybe need storing inside ImGuiWindow.
4755
79.1k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4756
4757
    // Find the window hovered by mouse:
4758
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4759
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4760
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4761
79.1k
    bool clear_hovered_windows = false;
4762
79.1k
    FindHoveredWindowEx(g.IO.MousePos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow);
4763
79.1k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4764
79.1k
    g.HoveredWindowBeforeClear = g.HoveredWindow;
4765
4766
    // Modal windows prevents mouse from hovering behind them.
4767
79.1k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4768
79.1k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4769
0
        clear_hovered_windows = true;
4770
4771
    // Disabled mouse hovering (we don't currently clear MousePos, we could)
4772
79.1k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4773
0
        clear_hovered_windows = true;
4774
4775
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4776
    // won't report hovering nor request capture even while dragging over our windows afterward.
4777
79.1k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4778
79.1k
    const bool has_open_modal = (modal_window != NULL);
4779
79.1k
    int mouse_earliest_down = -1;
4780
79.1k
    bool mouse_any_down = false;
4781
474k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4782
395k
    {
4783
395k
        if (io.MouseClicked[i])
4784
4.10k
        {
4785
4.10k
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4786
4.10k
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4787
4.10k
        }
4788
395k
        mouse_any_down |= io.MouseDown[i];
4789
395k
        if (io.MouseDown[i] || io.MouseReleased[i]) // Increase release frame for our evaluation of earliest button (#1392)
4790
93.2k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4791
78.8k
                mouse_earliest_down = i;
4792
395k
    }
4793
79.1k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4794
79.1k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4795
4796
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4797
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4798
79.1k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4799
79.1k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4800
49.7k
        clear_hovered_windows = true;
4801
4802
79.1k
    if (clear_hovered_windows)
4803
49.7k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4804
4805
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4806
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4807
79.1k
    if (g.WantCaptureMouseNextFrame != -1)
4808
0
    {
4809
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4810
0
    }
4811
79.1k
    else
4812
79.1k
    {
4813
79.1k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4814
79.1k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4815
79.1k
    }
4816
4817
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4818
79.1k
    io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4819
79.1k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4820
3.84k
        io.WantCaptureKeyboard = true;
4821
79.1k
    if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
4822
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4823
4824
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4825
79.1k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4826
79.1k
}
4827
4828
// Calling SetupDrawListSharedData() is followed by SetCurrentFont() which sets up the remaining data.
4829
static void SetupDrawListSharedData()
4830
79.1k
{
4831
79.1k
    ImGuiContext& g = *GImGui;
4832
79.1k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4833
79.1k
    for (ImGuiViewportP* viewport : g.Viewports)
4834
79.1k
        virtual_space.Add(viewport->GetMainRect());
4835
79.1k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4836
79.1k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4837
79.1k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4838
79.1k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4839
79.1k
    if (g.Style.AntiAliasedLines)
4840
79.1k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4841
79.1k
    if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines))
4842
79.1k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4843
79.1k
    if (g.Style.AntiAliasedFill)
4844
79.1k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4845
79.1k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4846
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4847
79.1k
}
4848
4849
void ImGui::NewFrame()
4850
79.1k
{
4851
79.1k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4852
79.1k
    ImGuiContext& g = *GImGui;
4853
4854
    // Remove pending delete hooks before frame start.
4855
    // This deferred removal avoid issues of removal while iterating the hook vector
4856
79.1k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4857
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4858
0
            g.Hooks.erase(&g.Hooks[n]);
4859
4860
79.1k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4861
4862
    // Check and assert for various common IO and Configuration mistakes
4863
79.1k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4864
79.1k
    ErrorCheckNewFrameSanityChecks();
4865
79.1k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4866
4867
    // Load settings on first frame, save settings when modified (after a delay)
4868
79.1k
    UpdateSettings();
4869
4870
79.1k
    g.Time += g.IO.DeltaTime;
4871
79.1k
    g.WithinFrameScope = true;
4872
79.1k
    g.FrameCount += 1;
4873
79.1k
    g.TooltipOverrideCount = 0;
4874
79.1k
    g.WindowsActiveCount = 0;
4875
79.1k
    g.MenusIdSubmittedThisFrame.resize(0);
4876
4877
    // Calculate frame-rate for the user, as a purely luxurious feature
4878
79.1k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4879
79.1k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4880
79.1k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4881
79.1k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4882
79.1k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4883
4884
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4885
79.1k
    g.InputEventsTrail.resize(0);
4886
79.1k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4887
4888
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4889
79.1k
    UpdateViewportsNewFrame();
4890
4891
    // Setup current font and draw list shared data
4892
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4893
79.1k
    g.IO.Fonts->Locked = true;
4894
79.1k
    SetupDrawListSharedData();
4895
79.1k
    SetCurrentFont(GetDefaultFont());
4896
79.1k
    IM_ASSERT(g.Font->IsLoaded());
4897
4898
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4899
79.1k
    for (ImGuiViewportP* viewport : g.Viewports)
4900
79.1k
    {
4901
79.1k
        viewport->DrawData = NULL;
4902
79.1k
        viewport->DrawDataP.Valid = false;
4903
79.1k
    }
4904
4905
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4906
79.1k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4907
16
        KeepAliveID(g.DragDropPayload.SourceId);
4908
4909
    // Update HoveredId data
4910
79.1k
    if (!g.HoveredIdPreviousFrame)
4911
79.0k
        g.HoveredIdTimer = 0.0f;
4912
79.1k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4913
79.0k
        g.HoveredIdNotActiveTimer = 0.0f;
4914
79.1k
    if (g.HoveredId)
4915
33
        g.HoveredIdTimer += g.IO.DeltaTime;
4916
79.1k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4917
33
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4918
79.1k
    g.HoveredIdPreviousFrame = g.HoveredId;
4919
79.1k
    g.HoveredId = 0;
4920
79.1k
    g.HoveredIdAllowOverlap = false;
4921
79.1k
    g.HoveredIdIsDisabled = false;
4922
4923
    // Clear ActiveID if the item is not alive anymore.
4924
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4925
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4926
79.1k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4927
0
    {
4928
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4929
0
        ClearActiveID();
4930
0
    }
4931
4932
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4933
79.1k
    if (g.ActiveId)
4934
58
        g.ActiveIdTimer += g.IO.DeltaTime;
4935
79.1k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4936
79.1k
    g.ActiveIdPreviousFrame = g.ActiveId;
4937
79.1k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4938
79.1k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4939
79.1k
    g.ActiveIdIsAlive = 0;
4940
79.1k
    g.ActiveIdHasBeenEditedThisFrame = false;
4941
79.1k
    g.ActiveIdPreviousFrameIsAlive = false;
4942
79.1k
    g.ActiveIdIsJustActivated = false;
4943
79.1k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4944
0
        g.TempInputId = 0;
4945
79.1k
    if (g.ActiveId == 0)
4946
79.0k
    {
4947
79.0k
        g.ActiveIdUsingNavDirMask = 0x00;
4948
79.0k
        g.ActiveIdUsingAllKeyboardKeys = false;
4949
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4950
        g.ActiveIdUsingNavInputMask = 0x00;
4951
#endif
4952
79.0k
    }
4953
4954
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4955
    if (g.ActiveId == 0)
4956
        g.ActiveIdUsingNavInputMask = 0;
4957
    else if (g.ActiveIdUsingNavInputMask != 0)
4958
    {
4959
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4960
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4961
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4962
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4963
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4964
            IM_ASSERT(0); // Other values unsupported
4965
    }
4966
#endif
4967
4968
    // Record when we have been stationary as this state is preserved while over same item.
4969
    // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
4970
    // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
4971
79.1k
    if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4972
0
        g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
4973
79.1k
    else if (g.HoverItemDelayId == 0)
4974
79.1k
        g.HoverItemUnlockedStationaryId = 0;
4975
79.1k
    if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4976
244
        g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
4977
78.8k
    else if (g.HoveredWindow == NULL)
4978
78.7k
        g.HoverWindowUnlockedStationaryId = 0;
4979
4980
    // Update hover delay for IsItemHovered() with delays and tooltips
4981
79.1k
    g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
4982
79.1k
    if (g.HoverItemDelayId != 0)
4983
0
    {
4984
0
        g.HoverItemDelayTimer += g.IO.DeltaTime;
4985
0
        g.HoverItemDelayClearTimer = 0.0f;
4986
0
        g.HoverItemDelayId = 0;
4987
0
    }
4988
79.1k
    else if (g.HoverItemDelayTimer > 0.0f)
4989
0
    {
4990
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4991
        // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
4992
0
        g.HoverItemDelayClearTimer += g.IO.DeltaTime;
4993
0
        if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
4994
0
            g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4995
0
    }
4996
4997
    // Drag and drop
4998
79.1k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4999
79.1k
    g.DragDropAcceptIdCurr = 0;
5000
79.1k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
5001
79.1k
    g.DragDropWithinSource = false;
5002
79.1k
    g.DragDropWithinTarget = false;
5003
79.1k
    g.DragDropHoldJustPressedId = 0;
5004
5005
    // Close popups on focus lost (currently wip/opt-in)
5006
    //if (g.IO.AppFocusLost)
5007
    //    ClosePopupsExceptModals();
5008
5009
    // Update keyboard input state
5010
79.1k
    UpdateKeyboardInputs();
5011
5012
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
5013
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
5014
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
5015
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
5016
5017
    // Update gamepad/keyboard navigation
5018
79.1k
    NavUpdate();
5019
5020
    // Update mouse input state
5021
79.1k
    UpdateMouseInputs();
5022
5023
    // Undocking
5024
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
5025
79.1k
    DockContextNewFrameUpdateUndocking(&g);
5026
5027
    // Find hovered window
5028
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
5029
79.1k
    UpdateHoveredWindowAndCaptureFlags();
5030
5031
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
5032
79.1k
    UpdateMouseMovingWindowNewFrame();
5033
5034
    // Background darkening/whitening
5035
79.1k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
5036
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
5037
79.1k
    else
5038
79.1k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
5039
5040
79.1k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
5041
79.1k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
5042
5043
    // Platform IME data: reset for the frame
5044
79.1k
    g.PlatformImeDataPrev = g.PlatformImeData;
5045
79.1k
    g.PlatformImeData.WantVisible = false;
5046
5047
    // Mouse wheel scrolling, scale
5048
79.1k
    UpdateMouseWheel();
5049
5050
    // Mark all windows as not visible and compact unused memory.
5051
79.1k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
5052
79.1k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
5053
79.1k
    for (ImGuiWindow* window : g.Windows)
5054
237k
    {
5055
237k
        window->WasActive = window->Active;
5056
237k
        window->Active = false;
5057
237k
        window->WriteAccessed = false;
5058
237k
        window->BeginCountPreviousFrame = window->BeginCount;
5059
237k
        window->BeginCount = 0;
5060
5061
        // Garbage collect transient buffers of recently unused windows
5062
237k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
5063
1
            GcCompactTransientWindowBuffers(window);
5064
237k
    }
5065
5066
    // Garbage collect transient buffers of recently unused tables
5067
79.1k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
5068
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
5069
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
5070
79.1k
    for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
5071
0
        if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
5072
0
            TableGcCompactTransientBuffers(&table_temp_data);
5073
79.1k
    if (g.GcCompactAll)
5074
0
        GcCompactTransientMiscBuffers();
5075
79.1k
    g.GcCompactAll = false;
5076
5077
    // Closing the focused window restore focus to the first active root window in descending z-order
5078
79.1k
    if (g.NavWindow && !g.NavWindow->WasActive)
5079
0
        FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
5080
5081
    // No window should be open at the beginning of the frame.
5082
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
5083
79.1k
    g.CurrentWindowStack.resize(0);
5084
79.1k
    g.BeginPopupStack.resize(0);
5085
79.1k
    g.ItemFlagsStack.resize(0);
5086
79.1k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
5087
79.1k
    g.GroupStack.resize(0);
5088
5089
    // Docking
5090
79.1k
    DockContextNewFrameUpdateDocking(&g);
5091
5092
    // [DEBUG] Update debug features
5093
79.1k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5094
79.1k
    UpdateDebugToolItemPicker();
5095
79.1k
    UpdateDebugToolStackQueries();
5096
79.1k
    UpdateDebugToolFlashStyleColor();
5097
79.1k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5098
0
    {
5099
0
        g.DebugLocateId = 0;
5100
0
        g.DebugBreakInLocateId = false;
5101
0
    }
5102
79.1k
    if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
5103
0
    {
5104
0
        DebugLog("(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
5105
0
        g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
5106
0
        g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
5107
0
    }
5108
79.1k
#endif
5109
5110
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
5111
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5112
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5113
79.1k
    g.WithinFrameScopeWithImplicitWindow = true;
5114
79.1k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
5115
79.1k
    Begin("Debug##Default");
5116
79.1k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5117
5118
    // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5119
    // allowing to validate correct Begin/End behavior in user code.
5120
79.1k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5121
79.1k
    if (g.IO.ConfigDebugBeginReturnValueLoop)
5122
0
        g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5123
79.1k
    else
5124
79.1k
        g.DebugBeginReturnValueCullDepth = -1;
5125
79.1k
#endif
5126
5127
79.1k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5128
79.1k
}
5129
5130
// FIXME: Add a more explicit sort order in the window structure.
5131
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5132
0
{
5133
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5134
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5135
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5136
0
        return d;
5137
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5138
0
        return d;
5139
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5140
0
}
5141
5142
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5143
237k
{
5144
237k
    out_sorted_windows->push_back(window);
5145
237k
    if (window->Active)
5146
90.5k
    {
5147
90.5k
        int count = window->DC.ChildWindows.Size;
5148
90.5k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5149
102k
        for (int i = 0; i < count; i++)
5150
11.4k
        {
5151
11.4k
            ImGuiWindow* child = window->DC.ChildWindows[i];
5152
11.4k
            if (child->Active)
5153
11.4k
                AddWindowToSortBuffer(out_sorted_windows, child);
5154
11.4k
        }
5155
90.5k
    }
5156
237k
}
5157
5158
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5159
90.5k
{
5160
90.5k
    ImGuiContext& g = *GImGui;
5161
90.5k
    ImGuiViewportP* viewport = window->Viewport;
5162
90.5k
    IM_ASSERT(viewport != NULL);
5163
90.5k
    g.IO.MetricsRenderWindows++;
5164
90.5k
    if (window->DrawList->_Splitter._Count > 1)
5165
0
        window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5166
90.5k
    ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5167
90.5k
    for (ImGuiWindow* child : window->DC.ChildWindows)
5168
11.4k
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5169
11.4k
            AddWindowToDrawData(child, layer);
5170
90.5k
}
5171
5172
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5173
79.1k
{
5174
79.1k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5175
79.1k
}
5176
5177
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5178
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5179
79.1k
{
5180
79.1k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5181
79.1k
}
5182
5183
static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5184
79.1k
{
5185
79.1k
    int n = builder->Layers[0]->Size;
5186
79.1k
    int full_size = n;
5187
158k
    for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5188
79.1k
        full_size += builder->Layers[i]->Size;
5189
79.1k
    builder->Layers[0]->resize(full_size);
5190
158k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5191
79.1k
    {
5192
79.1k
        ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5193
79.1k
        if (layer->empty())
5194
79.1k
            continue;
5195
0
        memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5196
0
        n += layer->Size;
5197
0
        layer->resize(0);
5198
0
    }
5199
79.1k
}
5200
5201
static void InitViewportDrawData(ImGuiViewportP* viewport)
5202
79.1k
{
5203
79.1k
    ImGuiIO& io = ImGui::GetIO();
5204
79.1k
    ImDrawData* draw_data = &viewport->DrawDataP;
5205
5206
79.1k
    viewport->DrawData = draw_data; // Make publicly accessible
5207
79.1k
    viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5208
79.1k
    viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5209
79.1k
    viewport->DrawDataBuilder.Layers[0]->resize(0);
5210
79.1k
    viewport->DrawDataBuilder.Layers[1]->resize(0);
5211
5212
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5213
    // and to allow applications/backends to easily skip rendering.
5214
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5215
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5216
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5217
79.1k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5218
5219
79.1k
    draw_data->Valid = true;
5220
79.1k
    draw_data->CmdListsCount = 0;
5221
79.1k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5222
79.1k
    draw_data->DisplayPos = viewport->Pos;
5223
79.1k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5224
79.1k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5225
79.1k
    draw_data->OwnerViewport = viewport;
5226
79.1k
}
5227
5228
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5229
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5230
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5231
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5232
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5233
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5234
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5235
339k
{
5236
339k
    ImGuiWindow* window = GetCurrentWindow();
5237
339k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5238
339k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5239
339k
}
5240
5241
void ImGui::PopClipRect()
5242
169k
{
5243
169k
    ImGuiWindow* window = GetCurrentWindow();
5244
169k
    window->DrawList->PopClipRect();
5245
169k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5246
169k
}
5247
5248
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5249
0
{
5250
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5251
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5252
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5253
0
    return window;
5254
0
}
5255
5256
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5257
0
{
5258
0
    if ((col & IM_COL32_A_MASK) == 0)
5259
0
        return;
5260
5261
0
    ImGuiViewportP* viewport = window->Viewport;
5262
0
    ImRect viewport_rect = viewport->GetMainRect();
5263
5264
    // Draw behind window by moving the draw command at the FRONT of the draw list
5265
0
    {
5266
        // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5267
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5268
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5269
0
        draw_list->ChannelsMerge();
5270
0
        if (draw_list->CmdBuffer.Size == 0)
5271
0
            draw_list->AddDrawCmd();
5272
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5273
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5274
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5275
0
        IM_ASSERT(cmd.ElemCount == 6);
5276
0
        draw_list->CmdBuffer.pop_back();
5277
0
        draw_list->CmdBuffer.push_front(cmd);
5278
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5279
0
        draw_list->PopClipRect();
5280
0
    }
5281
5282
    // Draw over sibling docking nodes in a same docking tree
5283
0
    if (window->RootWindow->DockIsActive)
5284
0
    {
5285
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5286
0
        draw_list->ChannelsMerge();
5287
0
        if (draw_list->CmdBuffer.Size == 0)
5288
0
            draw_list->AddDrawCmd();
5289
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5290
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5291
0
        draw_list->PopClipRect();
5292
0
    }
5293
0
}
5294
5295
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5296
0
{
5297
0
    ImGuiContext& g = *GImGui;
5298
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
5299
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5300
0
    {
5301
0
        ImGuiWindow* window = g.Windows[i];
5302
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5303
0
            continue;
5304
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5305
0
            break;
5306
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5307
0
            bottom_most_visible_window = window;
5308
0
    }
5309
0
    return bottom_most_visible_window;
5310
0
}
5311
5312
// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5313
// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5314
static void ImGui::RenderDimmedBackgrounds()
5315
79.1k
{
5316
79.1k
    ImGuiContext& g = *GImGui;
5317
79.1k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5318
79.1k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5319
79.1k
        return;
5320
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5321
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5322
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5323
0
        return;
5324
5325
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5326
0
    if (dim_bg_for_modal)
5327
0
    {
5328
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5329
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5330
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(modal_window->DC.ModalDimBgColor, g.DimBgRatio));
5331
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5332
0
    }
5333
0
    else if (dim_bg_for_window_list)
5334
0
    {
5335
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5336
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5337
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5338
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5339
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5340
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5341
5342
        // Draw border around CTRL+Tab target window
5343
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5344
0
        ImGuiViewport* viewport = window->Viewport;
5345
0
        float distance = g.FontSize;
5346
0
        ImRect bb = window->Rect();
5347
0
        bb.Expand(distance);
5348
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5349
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5350
0
        window->DrawList->ChannelsMerge();
5351
0
        if (window->DrawList->CmdBuffer.Size == 0)
5352
0
            window->DrawList->AddDrawCmd();
5353
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5354
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5355
0
        window->DrawList->PopClipRect();
5356
0
    }
5357
5358
    // Draw dimming background on _other_ viewports than the ones our windows are in
5359
0
    for (ImGuiViewportP* viewport : g.Viewports)
5360
0
    {
5361
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5362
0
            continue;
5363
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5364
0
            continue;
5365
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5366
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5367
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5368
0
    }
5369
0
}
5370
5371
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5372
void ImGui::EndFrame()
5373
158k
{
5374
158k
    ImGuiContext& g = *GImGui;
5375
158k
    IM_ASSERT(g.Initialized);
5376
5377
    // Don't process EndFrame() multiple times.
5378
158k
    if (g.FrameCountEnded == g.FrameCount)
5379
79.1k
        return;
5380
79.1k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5381
5382
79.1k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5383
5384
79.1k
    ErrorCheckEndFrameSanityChecks();
5385
5386
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5387
79.1k
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5388
79.1k
    if (g.IO.PlatformSetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5389
0
    {
5390
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5391
0
        IMGUI_DEBUG_LOG_IO("[io] Calling io.PlatformSetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5392
0
        if (viewport == NULL)
5393
0
            viewport = GetMainViewport();
5394
0
        g.IO.PlatformSetImeDataFn(&g, viewport, ime_data);
5395
0
    }
5396
5397
    // Hide implicit/fallback "Debug" window if it hasn't been used
5398
79.1k
    g.WithinFrameScopeWithImplicitWindow = false;
5399
79.1k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5400
79.1k
        g.CurrentWindow->Active = false;
5401
79.1k
    End();
5402
5403
    // Update navigation: CTRL+Tab, wrap-around requests
5404
79.1k
    NavEndFrame();
5405
5406
    // Update docking
5407
79.1k
    DockContextEndFrame(&g);
5408
5409
79.1k
    SetCurrentViewport(NULL, NULL);
5410
5411
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5412
79.1k
    if (g.DragDropActive)
5413
20
    {
5414
20
        bool is_delivered = g.DragDropPayload.Delivery;
5415
20
        bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_PayloadAutoExpire) || g.DragDropMouseButton == -1 || !IsMouseDown(g.DragDropMouseButton));
5416
20
        if (is_delivered || is_elapsed)
5417
2
            ClearDragDrop();
5418
20
    }
5419
5420
    // Drag and Drop: Fallback for missing source tooltip. This is not ideal but better than nothing.
5421
    // If you want to handle source item disappearing: instead of submitting your description tooltip
5422
    // in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot
5423
    // (e.g. end of your item loop, or before EndFrame) by reading payload data.
5424
    // In the typical case, the contents of drag tooltip should be possible to infer solely from payload data.
5425
79.1k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5426
0
    {
5427
0
        g.DragDropWithinSource = true;
5428
0
        SetTooltip("...");
5429
0
        g.DragDropWithinSource = false;
5430
0
    }
5431
5432
    // End frame
5433
79.1k
    g.WithinFrameScope = false;
5434
79.1k
    g.FrameCountEnded = g.FrameCount;
5435
5436
    // Initiate moving window + handle left-click and right-click focus
5437
79.1k
    UpdateMouseMovingWindowEndFrame();
5438
5439
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5440
79.1k
    UpdateViewportsEndFrame();
5441
5442
    // Sort the window list so that all child windows are after their parent
5443
    // We cannot do that on FocusWindow() because children may not exist yet
5444
79.1k
    g.WindowsTempSortBuffer.resize(0);
5445
79.1k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5446
79.1k
    for (ImGuiWindow* window : g.Windows)
5447
237k
    {
5448
237k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5449
11.4k
            continue;
5450
225k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5451
225k
    }
5452
5453
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5454
79.1k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5455
79.1k
    g.Windows.swap(g.WindowsTempSortBuffer);
5456
79.1k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5457
5458
    // Unlock font atlas
5459
79.1k
    g.IO.Fonts->Locked = false;
5460
5461
    // Clear Input data for next frame
5462
79.1k
    g.IO.MousePosPrev = g.IO.MousePos;
5463
79.1k
    g.IO.AppFocusLost = false;
5464
79.1k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5465
79.1k
    g.IO.InputQueueCharacters.resize(0);
5466
5467
79.1k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5468
79.1k
}
5469
5470
// Prepare the data for rendering so you can call GetDrawData()
5471
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5472
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5473
void ImGui::Render()
5474
79.1k
{
5475
79.1k
    ImGuiContext& g = *GImGui;
5476
79.1k
    IM_ASSERT(g.Initialized);
5477
5478
79.1k
    if (g.FrameCountEnded != g.FrameCount)
5479
79.1k
        EndFrame();
5480
79.1k
    if (g.FrameCountRendered == g.FrameCount)
5481
0
        return;
5482
79.1k
    g.FrameCountRendered = g.FrameCount;
5483
5484
79.1k
    g.IO.MetricsRenderWindows = 0;
5485
79.1k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5486
5487
    // Add background ImDrawList (for each active viewport)
5488
79.1k
    for (ImGuiViewportP* viewport : g.Viewports)
5489
79.1k
    {
5490
79.1k
        InitViewportDrawData(viewport);
5491
79.1k
        if (viewport->BgFgDrawLists[0] != NULL)
5492
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5493
79.1k
    }
5494
5495
    // Draw modal/window whitening backgrounds
5496
79.1k
    RenderDimmedBackgrounds();
5497
5498
    // Add ImDrawList to render
5499
79.1k
    ImGuiWindow* windows_to_render_top_most[2];
5500
79.1k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5501
79.1k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5502
79.1k
    for (ImGuiWindow* window : g.Windows)
5503
237k
    {
5504
237k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5505
237k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5506
79.1k
            AddRootWindowToDrawData(window);
5507
237k
    }
5508
237k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5509
158k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5510
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5511
5512
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5513
79.1k
    if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5514
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5515
5516
    // Setup ImDrawData structures for end-user
5517
79.1k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5518
79.1k
    for (ImGuiViewportP* viewport : g.Viewports)
5519
79.1k
    {
5520
79.1k
        FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
5521
5522
        // Add foreground ImDrawList (for each active viewport)
5523
79.1k
        if (viewport->BgFgDrawLists[1] != NULL)
5524
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5525
5526
        // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5527
79.1k
        ImDrawData* draw_data = &viewport->DrawDataP;
5528
79.1k
        IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5529
79.1k
        for (ImDrawList* draw_list : draw_data->CmdLists)
5530
90.5k
            draw_list->_PopUnusedDrawCmd();
5531
5532
79.1k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5533
79.1k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5534
79.1k
    }
5535
5536
79.1k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5537
79.1k
}
5538
5539
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5540
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5541
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5542
158k
{
5543
158k
    ImGuiContext& g = *GImGui;
5544
5545
158k
    const char* text_display_end;
5546
158k
    if (hide_text_after_double_hash)
5547
158k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5548
0
    else
5549
0
        text_display_end = text_end;
5550
5551
158k
    ImFont* font = g.Font;
5552
158k
    const float font_size = g.FontSize;
5553
158k
    if (text == text_display_end)
5554
0
        return ImVec2(0.0f, font_size);
5555
158k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5556
5557
    // Round
5558
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5559
    // FIXME: Investigate using ceilf or e.g.
5560
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5561
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5562
158k
    text_size.x = IM_TRUNC(text_size.x + 0.99999f);
5563
5564
158k
    return text_size;
5565
158k
}
5566
5567
// Find window given position, search front-to-back
5568
// - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow.
5569
// - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5570
//   with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5571
//   called, aka before the next Begin(). Moving window isn't affected.
5572
// - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here.
5573
void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window)
5574
79.1k
{
5575
79.1k
    ImGuiContext& g = *GImGui;
5576
79.1k
    ImGuiWindow* hovered_window = NULL;
5577
79.1k
    ImGuiWindow* hovered_window_under_moving_window = NULL;
5578
5579
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5580
79.1k
    ImGuiViewportP* backup_moving_window_viewport = NULL;
5581
79.1k
    if (find_first_and_in_any_viewport == false && g.MovingWindow)
5582
58
    {
5583
58
        backup_moving_window_viewport = g.MovingWindow->Viewport;
5584
58
        g.MovingWindow->Viewport = g.MouseViewport;
5585
58
        if (!(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5586
58
            hovered_window = g.MovingWindow;
5587
58
    }
5588
5589
79.1k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5590
79.1k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5591
314k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5592
236k
    {
5593
236k
        ImGuiWindow* window = g.Windows[i];
5594
236k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5595
236k
        if (!window->Active || window->Hidden)
5596
145k
            continue;
5597
90.5k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5598
0
            continue;
5599
90.5k
        IM_ASSERT(window->Viewport);
5600
90.5k
        if (window->Viewport != g.MouseViewport)
5601
0
            continue;
5602
5603
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5604
90.5k
        ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
5605
90.5k
        if (!window->OuterRectClipped.ContainsWithPad(pos, hit_padding))
5606
89.4k
            continue;
5607
5608
        // Support for one rectangular hole in any given window
5609
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5610
1.13k
        if (window->HitTestHoleSize.x != 0)
5611
0
        {
5612
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5613
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5614
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(pos))
5615
0
                continue;
5616
0
        }
5617
5618
1.13k
        if (find_first_and_in_any_viewport)
5619
0
        {
5620
0
            hovered_window = window;
5621
0
            break;
5622
0
        }
5623
1.13k
        else
5624
1.13k
        {
5625
1.13k
            if (hovered_window == NULL)
5626
1.08k
                hovered_window = window;
5627
1.13k
            IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5628
1.13k
            if (hovered_window_under_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5629
1.08k
                hovered_window_under_moving_window = window;
5630
1.13k
            if (hovered_window && hovered_window_under_moving_window)
5631
1.08k
                break;
5632
1.13k
        }
5633
1.13k
    }
5634
5635
79.1k
    *out_hovered_window = hovered_window;
5636
79.1k
    if (out_hovered_window_under_moving_window != NULL)
5637
79.1k
        *out_hovered_window_under_moving_window = hovered_window_under_moving_window;
5638
79.1k
    if (find_first_and_in_any_viewport == false && g.MovingWindow)
5639
58
        g.MovingWindow->Viewport = backup_moving_window_viewport;
5640
79.1k
}
5641
5642
bool ImGui::IsItemActive()
5643
158k
{
5644
158k
    ImGuiContext& g = *GImGui;
5645
158k
    if (g.ActiveId)
5646
110
        return g.ActiveId == g.LastItemData.ID;
5647
158k
    return false;
5648
158k
}
5649
5650
bool ImGui::IsItemActivated()
5651
0
{
5652
0
    ImGuiContext& g = *GImGui;
5653
0
    if (g.ActiveId)
5654
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5655
0
            return true;
5656
0
    return false;
5657
0
}
5658
5659
bool ImGui::IsItemDeactivated()
5660
0
{
5661
0
    ImGuiContext& g = *GImGui;
5662
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5663
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5664
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5665
0
}
5666
5667
bool ImGui::IsItemDeactivatedAfterEdit()
5668
0
{
5669
0
    ImGuiContext& g = *GImGui;
5670
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5671
0
}
5672
5673
// == GetItemID() == GetFocusID()
5674
bool ImGui::IsItemFocused()
5675
0
{
5676
0
    ImGuiContext& g = *GImGui;
5677
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5678
0
        return false;
5679
5680
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5681
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5682
0
    ImGuiWindow* window = g.CurrentWindow;
5683
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5684
0
        return false;
5685
5686
0
    return true;
5687
0
}
5688
5689
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5690
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5691
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5692
0
{
5693
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5694
0
}
5695
5696
bool ImGui::IsItemToggledOpen()
5697
0
{
5698
0
    ImGuiContext& g = *GImGui;
5699
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5700
0
}
5701
5702
bool ImGui::IsItemToggledSelection()
5703
0
{
5704
0
    ImGuiContext& g = *GImGui;
5705
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5706
0
}
5707
5708
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
5709
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
5710
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
5711
bool ImGui::IsAnyItemHovered()
5712
0
{
5713
0
    ImGuiContext& g = *GImGui;
5714
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5715
0
}
5716
5717
bool ImGui::IsAnyItemActive()
5718
0
{
5719
0
    ImGuiContext& g = *GImGui;
5720
0
    return g.ActiveId != 0;
5721
0
}
5722
5723
bool ImGui::IsAnyItemFocused()
5724
0
{
5725
0
    ImGuiContext& g = *GImGui;
5726
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5727
0
}
5728
5729
bool ImGui::IsItemVisible()
5730
0
{
5731
0
    ImGuiContext& g = *GImGui;
5732
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5733
0
}
5734
5735
bool ImGui::IsItemEdited()
5736
0
{
5737
0
    ImGuiContext& g = *GImGui;
5738
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5739
0
}
5740
5741
// Allow next item to be overlapped by subsequent items.
5742
// This works by requiring HoveredId to match for two subsequent frames,
5743
// so if a following items overwrite it our interactions will naturally be disabled.
5744
void ImGui::SetNextItemAllowOverlap()
5745
0
{
5746
0
    ImGuiContext& g = *GImGui;
5747
0
    g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
5748
0
}
5749
5750
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5751
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5752
// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5753
void ImGui::SetItemAllowOverlap()
5754
{
5755
    ImGuiContext& g = *GImGui;
5756
    ImGuiID id = g.LastItemData.ID;
5757
    if (g.HoveredId == id)
5758
        g.HoveredIdAllowOverlap = true;
5759
    if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5760
        g.ActiveIdAllowOverlap = true;
5761
}
5762
#endif
5763
5764
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5765
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5766
52
{
5767
52
    ImGuiContext& g = *GImGui;
5768
52
    IM_ASSERT(g.ActiveId != 0);
5769
52
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5770
52
    g.ActiveIdUsingAllKeyboardKeys = true;
5771
52
    NavMoveRequestCancel();
5772
52
}
5773
5774
ImGuiID ImGui::GetItemID()
5775
0
{
5776
0
    ImGuiContext& g = *GImGui;
5777
0
    return g.LastItemData.ID;
5778
0
}
5779
5780
ImVec2 ImGui::GetItemRectMin()
5781
0
{
5782
0
    ImGuiContext& g = *GImGui;
5783
0
    return g.LastItemData.Rect.Min;
5784
0
}
5785
5786
ImVec2 ImGui::GetItemRectMax()
5787
0
{
5788
0
    ImGuiContext& g = *GImGui;
5789
0
    return g.LastItemData.Rect.Max;
5790
0
}
5791
5792
ImVec2 ImGui::GetItemRectSize()
5793
0
{
5794
0
    ImGuiContext& g = *GImGui;
5795
0
    return g.LastItemData.Rect.GetSize();
5796
0
}
5797
5798
// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
5799
// ImGuiChildFlags_Border is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
5800
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5801
11.4k
{
5802
11.4k
    ImGuiID id = GetCurrentWindow()->GetID(str_id);
5803
11.4k
    return BeginChildEx(str_id, id, size_arg, child_flags, window_flags);
5804
11.4k
}
5805
5806
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5807
0
{
5808
0
    return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
5809
0
}
5810
5811
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5812
11.4k
{
5813
11.4k
    ImGuiContext& g = *GImGui;
5814
11.4k
    ImGuiWindow* parent_window = g.CurrentWindow;
5815
11.4k
    IM_ASSERT(id != 0);
5816
5817
    // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
5818
11.4k
    const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened;
5819
11.4k
    IM_UNUSED(ImGuiChildFlags_SupportedMask_);
5820
11.4k
    IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
5821
11.4k
    IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
5822
11.4k
    if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
5823
0
    {
5824
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5825
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5826
0
    }
5827
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5828
    if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
5829
        child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
5830
    if (window_flags & ImGuiWindowFlags_NavFlattened)
5831
        child_flags |= ImGuiChildFlags_NavFlattened;
5832
#endif
5833
11.4k
    if (child_flags & ImGuiChildFlags_AutoResizeX)
5834
0
        child_flags &= ~ImGuiChildFlags_ResizeX;
5835
11.4k
    if (child_flags & ImGuiChildFlags_AutoResizeY)
5836
0
        child_flags &= ~ImGuiChildFlags_ResizeY;
5837
5838
    // Set window flags
5839
11.4k
    window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
5840
11.4k
    window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
5841
11.4k
    if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
5842
0
        window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
5843
11.4k
    if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
5844
11.4k
        window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
5845
5846
    // Special framed style
5847
11.4k
    if (child_flags & ImGuiChildFlags_FrameStyle)
5848
0
    {
5849
0
        PushStyleColor(ImGuiCol_ChildBg, g.Style.Colors[ImGuiCol_FrameBg]);
5850
0
        PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding);
5851
0
        PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize);
5852
0
        PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding);
5853
0
        child_flags |= ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding;
5854
0
        window_flags |= ImGuiWindowFlags_NoMove;
5855
0
    }
5856
5857
    // Forward child flags
5858
11.4k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
5859
11.4k
    g.NextWindowData.ChildFlags = child_flags;
5860
5861
    // Forward size
5862
    // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
5863
    // (the alternative would to store conditional flags per axis, which is possible but more code)
5864
11.4k
    const ImVec2 size_avail = GetContentRegionAvail();
5865
11.4k
    const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
5866
11.4k
    const ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
5867
11.4k
    SetNextWindowSize(size);
5868
5869
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5870
    // FIXME: 2023/11/14: commented out shorted version. We had an issue with multiple ### in child window path names, which the trailing hash helped workaround.
5871
    // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
5872
11.4k
    const char* temp_window_name;
5873
    /*if (name && parent_window->IDStack.back() == parent_window->ID)
5874
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
5875
    else*/
5876
11.4k
    if (name)
5877
11.4k
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5878
0
    else
5879
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5880
5881
    // Set style
5882
11.4k
    const float backup_border_size = g.Style.ChildBorderSize;
5883
11.4k
    if ((child_flags & ImGuiChildFlags_Border) == 0)
5884
5.27k
        g.Style.ChildBorderSize = 0.0f;
5885
5886
    // Begin into window
5887
11.4k
    const bool ret = Begin(temp_window_name, NULL, window_flags);
5888
5889
    // Restore style
5890
11.4k
    g.Style.ChildBorderSize = backup_border_size;
5891
11.4k
    if (child_flags & ImGuiChildFlags_FrameStyle)
5892
0
    {
5893
0
        PopStyleVar(3);
5894
0
        PopStyleColor();
5895
0
    }
5896
5897
11.4k
    ImGuiWindow* child_window = g.CurrentWindow;
5898
11.4k
    child_window->ChildId = id;
5899
5900
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5901
    // While this is not really documented/defined, it seems that the expected thing to do.
5902
11.4k
    if (child_window->BeginCount == 1)
5903
11.4k
        parent_window->DC.CursorPos = child_window->Pos;
5904
5905
    // Process navigation-in immediately so NavInit can run on first frame
5906
    // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
5907
11.4k
    const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
5908
11.4k
    if (g.ActiveId == temp_id_for_activation)
5909
0
        ClearActiveID();
5910
11.4k
    if (g.NavActivateId == id && !(child_flags & ImGuiChildFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5911
11
    {
5912
11
        FocusWindow(child_window);
5913
11
        NavInitWindow(child_window, false);
5914
11
        SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5915
11
        g.ActiveIdSource = g.NavInputSource;
5916
11
    }
5917
11.4k
    return ret;
5918
11.4k
}
5919
5920
void ImGui::EndChild()
5921
11.4k
{
5922
11.4k
    ImGuiContext& g = *GImGui;
5923
11.4k
    ImGuiWindow* child_window = g.CurrentWindow;
5924
5925
11.4k
    IM_ASSERT(g.WithinEndChild == false);
5926
11.4k
    IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5927
5928
11.4k
    g.WithinEndChild = true;
5929
11.4k
    ImVec2 child_size = child_window->Size;
5930
11.4k
    End();
5931
11.4k
    if (child_window->BeginCount == 1)
5932
11.4k
    {
5933
11.4k
        ImGuiWindow* parent_window = g.CurrentWindow;
5934
11.4k
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
5935
11.4k
        ItemSize(child_size);
5936
11.4k
        const bool nav_flattened = (child_window->ChildFlags & ImGuiChildFlags_NavFlattened) != 0;
5937
11.4k
        if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !nav_flattened)
5938
8.73k
        {
5939
8.73k
            ItemAdd(bb, child_window->ChildId);
5940
8.73k
            RenderNavHighlight(bb, child_window->ChildId);
5941
5942
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5943
8.73k
            if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
5944
4.45k
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_Compact);
5945
8.73k
        }
5946
2.75k
        else
5947
2.75k
        {
5948
            // Not navigable into
5949
            // - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs.
5950
            // - We could later decide to not apply this path if ImGuiChildFlags_FrameStyle or ImGuiChildFlags_Borders is set.
5951
2.75k
            ItemAdd(bb, child_window->ChildId, NULL, ImGuiItemFlags_NoNav);
5952
5953
            // But when flattened we directly reach items, adjust active layer mask accordingly
5954
2.75k
            if (nav_flattened)
5955
0
                parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
5956
2.75k
        }
5957
11.4k
        if (g.HoveredWindow == child_window)
5958
3
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5959
11.4k
    }
5960
11.4k
    g.WithinEndChild = false;
5961
11.4k
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5962
11.4k
}
5963
5964
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5965
6
{
5966
6
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5967
6
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5968
6
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5969
6
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5970
6
}
5971
5972
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5973
169k
{
5974
169k
    ImGuiContext& g = *GImGui;
5975
169k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5976
169k
}
5977
5978
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5979
169k
{
5980
169k
    ImGuiID id = ImHashStr(name);
5981
169k
    return FindWindowByID(id);
5982
169k
}
5983
5984
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5985
0
{
5986
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5987
0
    window->ViewportPos = main_viewport->Pos;
5988
0
    if (settings->ViewportId)
5989
0
    {
5990
0
        window->ViewportId = settings->ViewportId;
5991
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5992
0
    }
5993
0
    window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5994
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
5995
0
        window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
5996
0
    window->Collapsed = settings->Collapsed;
5997
0
    window->DockId = settings->DockId;
5998
0
    window->DockOrder = settings->DockOrder;
5999
0
}
6000
6001
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
6002
169k
{
6003
169k
    ImGuiContext& g = *GImGui;
6004
6005
169k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
6006
169k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
6007
169k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
6008
2
    {
6009
2
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
6010
2
        g.WindowsFocusOrder.push_back(window);
6011
2
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
6012
2
    }
6013
169k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
6014
0
    {
6015
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
6016
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
6017
0
            g.WindowsFocusOrder[n]->FocusOrder--;
6018
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
6019
0
        window->FocusOrder = -1;
6020
0
    }
6021
169k
    window->IsExplicitChild = new_is_explicit_child;
6022
169k
}
6023
6024
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6025
3
{
6026
    // Initial window state with e.g. default/arbitrary window position
6027
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
6028
3
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6029
3
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
6030
3
    window->Size = window->SizeFull = ImVec2(0, 0);
6031
3
    window->ViewportPos = main_viewport->Pos;
6032
3
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
6033
6034
3
    if (settings != NULL)
6035
0
    {
6036
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
6037
0
        ApplyWindowSettings(window, settings);
6038
0
    }
6039
3
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
6040
6041
3
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
6042
0
    {
6043
0
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
6044
0
        window->AutoFitOnlyGrows = false;
6045
0
    }
6046
3
    else
6047
3
    {
6048
3
        if (window->Size.x <= 0.0f)
6049
3
            window->AutoFitFramesX = 2;
6050
3
        if (window->Size.y <= 0.0f)
6051
3
            window->AutoFitFramesY = 2;
6052
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
6053
3
    }
6054
3
}
6055
6056
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
6057
3
{
6058
    // Create window the first time
6059
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
6060
3
    ImGuiContext& g = *GImGui;
6061
3
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
6062
3
    window->Flags = flags;
6063
3
    g.WindowsById.SetVoidPtr(window->ID, window);
6064
6065
3
    ImGuiWindowSettings* settings = NULL;
6066
3
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
6067
2
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
6068
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
6069
6070
3
    InitOrLoadWindowSettings(window, settings);
6071
6072
3
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
6073
0
        g.Windows.push_front(window); // Quite slow but rare and only once
6074
3
    else
6075
3
        g.Windows.push_back(window);
6076
6077
3
    return window;
6078
3
}
6079
6080
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
6081
0
{
6082
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
6083
0
}
6084
6085
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
6086
509k
{
6087
509k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
6088
509k
}
6089
6090
static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
6091
509k
{
6092
    // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
6093
    // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
6094
    // Perhaps should tend further a neater test for this.
6095
509k
    ImGuiContext& g = *GImGui;
6096
509k
    ImVec2 size_min;
6097
509k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
6098
34.4k
    {
6099
34.4k
        size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
6100
34.4k
        size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
6101
34.4k
    }
6102
474k
    else
6103
474k
    {
6104
474k
        size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
6105
474k
        size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
6106
474k
    }
6107
6108
    // Reduce artifacts with very small windows
6109
509k
    ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
6110
509k
    size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight + window_for_height->MenuBarHeight + ImMax(0.0f, g.Style.WindowRounding - 1.0f));
6111
509k
    return size_min;
6112
509k
}
6113
6114
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
6115
339k
{
6116
339k
    ImGuiContext& g = *GImGui;
6117
339k
    ImVec2 new_size = size_desired;
6118
339k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
6119
0
    {
6120
        // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
6121
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
6122
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
6123
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
6124
0
        if (g.NextWindowData.SizeCallback)
6125
0
        {
6126
0
            ImGuiSizeCallbackData data;
6127
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
6128
0
            data.Pos = window->Pos;
6129
0
            data.CurrentSize = window->SizeFull;
6130
0
            data.DesiredSize = new_size;
6131
0
            g.NextWindowData.SizeCallback(&data);
6132
0
            new_size = data.DesiredSize;
6133
0
        }
6134
0
        new_size.x = IM_TRUNC(new_size.x);
6135
0
        new_size.y = IM_TRUNC(new_size.y);
6136
0
    }
6137
6138
    // Minimum size
6139
339k
    ImVec2 size_min = CalcWindowMinSize(window);
6140
339k
    return ImMax(new_size, size_min);
6141
339k
}
6142
6143
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6144
169k
{
6145
169k
    bool preserve_old_content_sizes = false;
6146
169k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6147
67.6k
        preserve_old_content_sizes = true;
6148
102k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6149
0
        preserve_old_content_sizes = true;
6150
169k
    if (preserve_old_content_sizes)
6151
67.6k
    {
6152
67.6k
        *content_size_current = window->ContentSize;
6153
67.6k
        *content_size_ideal = window->ContentSizeIdeal;
6154
67.6k
        return;
6155
67.6k
    }
6156
6157
102k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6158
102k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6159
102k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6160
102k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6161
102k
}
6162
6163
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6164
169k
{
6165
169k
    ImGuiContext& g = *GImGui;
6166
169k
    ImGuiStyle& style = g.Style;
6167
169k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6168
169k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6169
169k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
6170
169k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6171
169k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
6172
0
    {
6173
        // Tooltip always resize
6174
0
        return size_desired;
6175
0
    }
6176
169k
    else
6177
169k
    {
6178
        // Maximum window size is determined by the viewport size or monitor size
6179
169k
        ImVec2 size_min = CalcWindowMinSize(window);
6180
169k
        ImVec2 size_max = ImVec2(FLT_MAX, FLT_MAX);
6181
6182
        // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction
6183
169k
        if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || (window->Flags & ImGuiWindowFlags_Popup) != 0)
6184
158k
        {
6185
158k
            if (!window->ViewportOwned)
6186
158k
                size_max = ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6187
158k
            const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6188
158k
            if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
6189
0
                size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6190
158k
        }
6191
6192
169k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, size_max));
6193
6194
        // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars,
6195
        // we may need to compute/store three variants of size_auto_fit, for x/y/xy.
6196
        // Here we implement a workaround for child windows only, but a full solution would apply to normal windows as well:
6197
169k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & ImGuiChildFlags_ResizeY))
6198
0
            size_auto_fit.y = window->SizeFull.y;
6199
169k
        else if (!(window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->ChildFlags & ImGuiChildFlags_ResizeY))
6200
0
            size_auto_fit.x = window->SizeFull.x;
6201
6202
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6203
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6204
169k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6205
169k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6206
169k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6207
169k
        if (will_have_scrollbar_x)
6208
11.4k
            size_auto_fit.y += style.ScrollbarSize;
6209
169k
        if (will_have_scrollbar_y)
6210
67.7k
            size_auto_fit.x += style.ScrollbarSize;
6211
169k
        return size_auto_fit;
6212
169k
    }
6213
169k
}
6214
6215
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6216
0
{
6217
0
    ImVec2 size_contents_current;
6218
0
    ImVec2 size_contents_ideal;
6219
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6220
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6221
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6222
0
    return size_final;
6223
0
}
6224
6225
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6226
102k
{
6227
102k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6228
0
        return ImGuiCol_PopupBg;
6229
102k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6230
11.4k
        return ImGuiCol_ChildBg;
6231
90.5k
    return ImGuiCol_WindowBg;
6232
102k
}
6233
6234
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6235
0
{
6236
0
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
6237
0
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6238
0
    ImVec2 size_expected = pos_max - pos_min;
6239
0
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6240
0
    *out_pos = pos_min;
6241
0
    if (corner_norm.x == 0.0f)
6242
0
        out_pos->x -= (size_constrained.x - size_expected.x);
6243
0
    if (corner_norm.y == 0.0f)
6244
0
        out_pos->y -= (size_constrained.y - size_expected.y);
6245
0
    *out_size = size_constrained;
6246
0
}
6247
6248
// Data for resizing from resize grip / corner
6249
struct ImGuiResizeGripDef
6250
{
6251
    ImVec2  CornerPosN;
6252
    ImVec2  InnerDir;
6253
    int     AngleMin12, AngleMax12;
6254
};
6255
static const ImGuiResizeGripDef resize_grip_def[4] =
6256
{
6257
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
6258
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
6259
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
6260
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
6261
};
6262
6263
// Data for resizing from borders
6264
struct ImGuiResizeBorderDef
6265
{
6266
    ImVec2  InnerDir;               // Normal toward inside
6267
    ImVec2  SegmentN1, SegmentN2;   // End positions, normalized (0,0: upper left)
6268
    float   OuterAngle;             // Angle toward outside
6269
};
6270
static const ImGuiResizeBorderDef resize_border_def[4] =
6271
{
6272
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6273
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6274
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6275
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
6276
};
6277
6278
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6279
45.9k
{
6280
45.9k
    ImRect rect = window->Rect();
6281
45.9k
    if (thickness == 0.0f)
6282
8
        rect.Max -= ImVec2(1, 1);
6283
45.9k
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
6284
34.4k
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
6285
22.9k
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
6286
11.4k
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
6287
0
    IM_ASSERT(0);
6288
0
    return ImRect();
6289
11.4k
}
6290
6291
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6292
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6293
0
{
6294
0
    IM_ASSERT(n >= 0 && n < 4);
6295
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6296
0
    id = ImHashStr("#RESIZE", 0, id);
6297
0
    id = ImHashData(&n, sizeof(int), id);
6298
0
    return id;
6299
0
}
6300
6301
// Borders (Left, Right, Up, Down)
6302
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6303
0
{
6304
0
    IM_ASSERT(dir >= 0 && dir < 4);
6305
0
    int n = (int)dir + 4;
6306
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6307
0
    id = ImHashStr("#RESIZE", 0, id);
6308
0
    id = ImHashData(&n, sizeof(int), id);
6309
0
    return id;
6310
0
}
6311
6312
// Handle resize for: Resize Grips, Borders, Gamepad
6313
// Return true when using auto-fit (double-click on resize grip)
6314
static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6315
102k
{
6316
102k
    ImGuiContext& g = *GImGui;
6317
102k
    ImGuiWindowFlags flags = window->Flags;
6318
6319
102k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6320
11.4k
        return false;
6321
90.5k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6322
79.1k
        return false;
6323
6324
11.4k
    int ret_auto_fit_mask = 0x00;
6325
11.4k
    const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6326
11.4k
    const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
6327
11.4k
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6328
6329
11.4k
    ImRect clamp_rect = visibility_rect;
6330
11.4k
    const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6331
11.4k
    if (window_move_from_title_bar)
6332
0
        clamp_rect.Min.y -= window->TitleBarHeight;
6333
6334
11.4k
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
6335
11.4k
    ImVec2 size_target(FLT_MAX, FLT_MAX);
6336
6337
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6338
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6339
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6340
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
6341
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6342
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6343
11.4k
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6344
11.4k
    if (clip_with_viewport_rect)
6345
11.4k
        window->ClipRect = window->Viewport->GetMainRect();
6346
6347
    // Resize grips and borders are on layer 1
6348
11.4k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6349
6350
    // Manual resize grips
6351
11.4k
    PushID("#RESIZE");
6352
34.4k
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6353
22.9k
    {
6354
22.9k
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6355
22.9k
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6356
6357
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6358
22.9k
        bool hovered, held;
6359
22.9k
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6360
22.9k
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6361
22.9k
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6362
22.9k
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6363
22.9k
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6364
22.9k
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6365
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6366
22.9k
        if (hovered || held)
6367
0
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6368
6369
22.9k
        if (held && g.IO.MouseDoubleClicked[0])
6370
0
        {
6371
            // Auto-fit when double-clicking
6372
0
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6373
0
            ret_auto_fit_mask = 0x03; // Both axises
6374
0
            ClearActiveID();
6375
0
        }
6376
22.9k
        else if (held)
6377
0
        {
6378
            // Resize from any of the four corners
6379
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6380
0
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX);
6381
0
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
6382
0
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6383
0
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6384
0
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6385
0
        }
6386
6387
        // Only lower-left grip is visible before hovering/activating
6388
22.9k
        if (resize_grip_n == 0 || held || hovered)
6389
11.4k
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6390
22.9k
    }
6391
6392
11.4k
    int resize_border_mask = 0x00;
6393
11.4k
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
6394
0
        resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
6395
11.4k
    else
6396
11.4k
        resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
6397
57.4k
    for (int border_n = 0; border_n < 4; border_n++)
6398
45.9k
    {
6399
45.9k
        if ((resize_border_mask & (1 << border_n)) == 0)
6400
0
            continue;
6401
45.9k
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6402
45.9k
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6403
6404
45.9k
        bool hovered, held;
6405
45.9k
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6406
45.9k
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6407
45.9k
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6408
45.9k
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6409
        //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6410
45.9k
        if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
6411
13
            hovered = false;
6412
45.9k
        if (hovered || held)
6413
8
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6414
45.9k
        if (held && g.IO.MouseDoubleClicked[0])
6415
0
        {
6416
            // Double-clicking bottom or right border auto-fit on this axis
6417
            // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one side may be auto-fit when calculating scrollbars.
6418
            // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
6419
0
            if (border_n == 1 || border_n == 3) // Right and bottom border
6420
0
            {
6421
0
                size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis];
6422
0
                ret_auto_fit_mask |= (1 << axis);
6423
0
                hovered = held = false; // So border doesn't show highlighted at new position
6424
0
            }
6425
0
            ClearActiveID();
6426
0
        }
6427
45.9k
        else if (held)
6428
0
        {
6429
            // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
6430
            // Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually.
6431
            // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
6432
0
            const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false, true));
6433
0
            if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
6434
0
            {
6435
0
                g.WindowResizeBorderExpectedRect = border_rect;
6436
0
                g.WindowResizeRelativeMode = false;
6437
0
            }
6438
0
            if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0)
6439
0
                g.WindowResizeRelativeMode = true;
6440
6441
0
            const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
6442
0
            const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
6443
0
            const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above.
6444
6445
            // Use absolute mode position
6446
0
            ImVec2 border_target = window->Pos;
6447
0
            border_target[axis] = border_target_abs_mode_for_axis;
6448
6449
            // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
6450
0
            bool ignore_resize = false;
6451
0
            if (g.WindowResizeRelativeMode)
6452
0
            {
6453
                //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
6454
0
                border_target[axis] = border_target_rel_mode_for_axis;
6455
0
                if (g.IO.MouseDelta[axis] == 0.0f || (g.IO.MouseDelta[axis] > 0.0f) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis))
6456
0
                    ignore_resize = true;
6457
0
            }
6458
6459
            // Clamp, apply
6460
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
6461
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6462
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6463
0
            if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
6464
0
            {
6465
0
                ImGuiWindow* parent_window = window->ParentWindow;
6466
0
                ImGuiWindowFlags parent_flags = parent_window->Flags;
6467
0
                ImRect border_limit_rect = parent_window->InnerRect;
6468
0
                border_limit_rect.Expand(ImVec2(-ImMax(parent_window->WindowPadding.x, parent_window->WindowBorderSize), -ImMax(parent_window->WindowPadding.y, parent_window->WindowBorderSize)));
6469
0
                if ((axis == ImGuiAxis_X) && ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar)))
6470
0
                    border_target.x = ImClamp(border_target.x, border_limit_rect.Min.x, border_limit_rect.Max.x);
6471
0
                if ((axis == ImGuiAxis_Y) && (parent_flags & ImGuiWindowFlags_NoScrollbar))
6472
0
                    border_target.y = ImClamp(border_target.y, border_limit_rect.Min.y, border_limit_rect.Max.y);
6473
0
            }
6474
0
            if (!ignore_resize)
6475
0
                CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6476
0
        }
6477
45.9k
        if (hovered)
6478
8
            *border_hovered = border_n;
6479
45.9k
        if (held)
6480
0
            *border_held = border_n;
6481
45.9k
    }
6482
11.4k
    PopID();
6483
6484
    // Restore nav layer
6485
11.4k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6486
6487
    // Navigation resize (keyboard/gamepad)
6488
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6489
    // Not even sure the callback works here.
6490
11.4k
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6491
0
    {
6492
0
        ImVec2 nav_resize_dir;
6493
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6494
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6495
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6496
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6497
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6498
0
        {
6499
0
            const float NAV_RESIZE_SPEED = 600.0f;
6500
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6501
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6502
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6503
0
            g.NavWindowingToggleLayer = false;
6504
0
            g.NavDisableMouseHover = true;
6505
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6506
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
6507
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6508
0
            {
6509
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6510
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6511
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6512
0
            }
6513
0
        }
6514
0
    }
6515
6516
    // Apply back modified position/size to window
6517
11.4k
    const ImVec2 curr_pos = window->Pos;
6518
11.4k
    const ImVec2 curr_size = window->SizeFull;
6519
11.4k
    if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x))
6520
0
        window->Size.x = window->SizeFull.x = size_target.x;
6521
11.4k
    if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y))
6522
0
        window->Size.y = window->SizeFull.y = size_target.y;
6523
11.4k
    if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(pos_target.x))
6524
0
        window->Pos.x = ImTrunc(pos_target.x);
6525
11.4k
    if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(pos_target.y))
6526
0
        window->Pos.y = ImTrunc(pos_target.y);
6527
11.4k
    if (curr_pos.x != window->Pos.x || curr_pos.y != window->Pos.y || curr_size.x != window->SizeFull.x || curr_size.y != window->SizeFull.y)
6528
0
        MarkIniSettingsDirty(window);
6529
6530
    // Recalculate next expected border expected coordinates
6531
11.4k
    if (*border_held != -1)
6532
0
        g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6533
6534
11.4k
    return ret_auto_fit_mask;
6535
90.5k
}
6536
6537
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6538
158k
{
6539
158k
    ImGuiContext& g = *GImGui;
6540
158k
    ImVec2 size_for_clamping = window->Size;
6541
158k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && window->DockNodeAsHost)
6542
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6543
158k
    else if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6544
0
        size_for_clamping.y = window->TitleBarHeight;
6545
158k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6546
158k
}
6547
6548
static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
6549
8
{
6550
8
    const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6551
8
    const float rounding = window->WindowRounding;
6552
8
    const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f);
6553
8
    window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6554
8
    window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6555
8
    window->DrawList->PathStroke(border_col, ImDrawFlags_None, border_size);
6556
8
}
6557
6558
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6559
102k
{
6560
102k
    ImGuiContext& g = *GImGui;
6561
102k
    const float border_size = window->WindowBorderSize;
6562
102k
    const ImU32 border_col = GetColorU32(ImGuiCol_Border);
6563
102k
    if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
6564
96.8k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, border_col, window->WindowRounding, 0, window->WindowBorderSize);
6565
5.27k
    else if (border_size > 0.0f)
6566
0
    {
6567
0
        if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
6568
0
            RenderWindowOuterSingleBorder(window, 1, border_col, border_size);
6569
0
        if (window->ChildFlags & ImGuiChildFlags_ResizeY)
6570
0
            RenderWindowOuterSingleBorder(window, 3, border_col, border_size);
6571
0
    }
6572
102k
    if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
6573
8
    {
6574
8
        const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
6575
8
        const ImU32 border_col_resizing = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
6576
8
        RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0f, window->WindowBorderSize)); // Thicker than usual
6577
8
    }
6578
102k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6579
0
    {
6580
0
        float y = window->Pos.y + window->TitleBarHeight - 1;
6581
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), border_col, g.Style.FrameBorderSize);
6582
0
    }
6583
102k
}
6584
6585
// Draw background and borders
6586
// Draw and handle scrollbars
6587
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6588
169k
{
6589
169k
    ImGuiContext& g = *GImGui;
6590
169k
    ImGuiStyle& style = g.Style;
6591
169k
    ImGuiWindowFlags flags = window->Flags;
6592
6593
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6594
169k
    IM_ASSERT(window->BeginCount == 0);
6595
169k
    window->SkipItems = false;
6596
6597
    // Draw window + handle manual resize
6598
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6599
169k
    const float window_rounding = window->WindowRounding;
6600
169k
    const float window_border_size = window->WindowBorderSize;
6601
169k
    if (window->Collapsed)
6602
67.6k
    {
6603
        // Title bar only
6604
67.6k
        const float backup_border_size = style.FrameBorderSize;
6605
67.6k
        g.Style.FrameBorderSize = window->WindowBorderSize;
6606
67.6k
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6607
67.6k
        if (window->ViewportOwned)
6608
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6609
67.6k
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6610
67.6k
        g.Style.FrameBorderSize = backup_border_size;
6611
67.6k
    }
6612
102k
    else
6613
102k
    {
6614
        // Window background
6615
102k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6616
102k
        {
6617
102k
            bool is_docking_transparent_payload = false;
6618
102k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6619
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6620
0
                    is_docking_transparent_payload = true;
6621
6622
102k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6623
102k
            if (window->ViewportOwned)
6624
0
            {
6625
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6626
0
                if (is_docking_transparent_payload)
6627
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6628
0
            }
6629
102k
            else
6630
102k
            {
6631
                // Adjust alpha. For docking
6632
102k
                bool override_alpha = false;
6633
102k
                float alpha = 1.0f;
6634
102k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6635
0
                {
6636
0
                    alpha = g.NextWindowData.BgAlphaVal;
6637
0
                    override_alpha = true;
6638
0
                }
6639
102k
                if (is_docking_transparent_payload)
6640
0
                {
6641
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6642
0
                    override_alpha = true;
6643
0
                }
6644
102k
                if (override_alpha)
6645
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6646
102k
            }
6647
6648
            // Render, for docked windows and host windows we ensure bg goes before decorations
6649
102k
            if (window->DockIsActive)
6650
0
                window->DockNode->LastBgColor = bg_col;
6651
102k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6652
102k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6653
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6654
102k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6655
102k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6656
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6657
102k
        }
6658
102k
        if (window->DockIsActive)
6659
0
            window->DockNode->IsBgDrawnThisFrame = true;
6660
6661
        // Title bar
6662
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6663
        // in order for their pos/size to be matching their undocking state.)
6664
102k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6665
90.5k
        {
6666
90.5k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6667
90.5k
            if (window->ViewportOwned)
6668
0
                title_bar_col |= IM_COL32_A_MASK; // No alpha
6669
90.5k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6670
90.5k
        }
6671
6672
        // Menu bar
6673
102k
        if (flags & ImGuiWindowFlags_MenuBar)
6674
0
        {
6675
0
            ImRect menu_bar_rect = window->MenuBarRect();
6676
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6677
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6678
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6679
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6680
0
        }
6681
6682
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6683
102k
        ImGuiDockNode* node = window->DockNode;
6684
102k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6685
0
        {
6686
0
            float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f);
6687
0
            float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f);
6688
0
            ImVec2 p = node->Pos;
6689
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6690
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6691
0
            KeepAliveID(unhide_id);
6692
0
            bool hovered, held;
6693
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6694
0
                node->WantHiddenTabBarToggle = true;
6695
0
            else if (held && IsMouseDragging(0))
6696
0
                StartMouseMovingWindowOrNode(window, node, true); // Undock from tab-bar triangle = same as window/collapse menu button
6697
6698
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6699
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6700
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6701
0
        }
6702
6703
        // Scrollbars
6704
102k
        if (window->ScrollbarX)
6705
11.4k
            Scrollbar(ImGuiAxis_X);
6706
102k
        if (window->ScrollbarY)
6707
9.13k
            Scrollbar(ImGuiAxis_Y);
6708
6709
        // Render resize grips (after their input handling so we don't have a frame of latency)
6710
102k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6711
90.5k
        {
6712
271k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6713
181k
            {
6714
181k
                const ImU32 col = resize_grip_col[resize_grip_n];
6715
181k
                if ((col & IM_COL32_A_MASK) == 0)
6716
169k
                    continue;
6717
11.4k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6718
11.4k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6719
11.4k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6720
11.4k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6721
11.4k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6722
11.4k
                window->DrawList->PathFillConvex(col);
6723
11.4k
            }
6724
90.5k
        }
6725
6726
        // Borders (for dock node host they will be rendered over after the tab bar)
6727
102k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6728
102k
            RenderWindowOuterBorders(window);
6729
102k
    }
6730
169k
}
6731
6732
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6733
// Render title text, collapse button, close button
6734
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6735
158k
{
6736
158k
    ImGuiContext& g = *GImGui;
6737
158k
    ImGuiStyle& style = g.Style;
6738
158k
    ImGuiWindowFlags flags = window->Flags;
6739
6740
158k
    const bool has_close_button = (p_open != NULL);
6741
158k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6742
6743
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6744
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6745
158k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6746
158k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6747
158k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6748
6749
    // Layout buttons
6750
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6751
158k
    float pad_l = style.FramePadding.x;
6752
158k
    float pad_r = style.FramePadding.x;
6753
158k
    float button_sz = g.FontSize;
6754
158k
    ImVec2 close_button_pos;
6755
158k
    ImVec2 collapse_button_pos;
6756
158k
    if (has_close_button)
6757
0
    {
6758
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6759
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6760
0
    }
6761
158k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6762
0
    {
6763
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6764
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6765
0
    }
6766
158k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6767
158k
    {
6768
158k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
6769
158k
        pad_l += button_sz + style.ItemInnerSpacing.x;
6770
158k
    }
6771
6772
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6773
158k
    if (has_collapse_button)
6774
158k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6775
1
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6776
6777
    // Close button
6778
158k
    if (has_close_button)
6779
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6780
0
            *p_open = false;
6781
6782
158k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6783
158k
    g.CurrentItemFlags = item_flags_backup;
6784
6785
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6786
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6787
158k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6788
158k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6789
6790
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6791
    // while uncentered title text will still reach edges correctly.
6792
158k
    if (pad_l > style.FramePadding.x)
6793
158k
        pad_l += g.Style.ItemInnerSpacing.x;
6794
158k
    if (pad_r > style.FramePadding.x)
6795
0
        pad_r += g.Style.ItemInnerSpacing.x;
6796
158k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6797
0
    {
6798
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6799
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6800
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6801
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6802
0
    }
6803
6804
158k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6805
158k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6806
158k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6807
0
    {
6808
0
        ImVec2 marker_pos;
6809
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6810
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6811
0
        if (marker_pos.x > layout_r.Min.x)
6812
0
        {
6813
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6814
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6815
0
        }
6816
0
    }
6817
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6818
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6819
158k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6820
158k
}
6821
6822
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6823
169k
{
6824
169k
    window->ParentWindow = parent_window;
6825
169k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6826
169k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6827
11.4k
    {
6828
11.4k
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6829
11.4k
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6830
11.4k
            window->RootWindow = parent_window->RootWindow;
6831
11.4k
    }
6832
169k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6833
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6834
169k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6835
11.4k
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6836
169k
    while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened)
6837
0
    {
6838
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6839
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6840
0
    }
6841
169k
}
6842
6843
// [EXPERIMENTAL] Called by Begin(). NextWindowData is valid at this point.
6844
// This is designed as a toy/test-bed for
6845
void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window)
6846
169k
{
6847
169k
    ImGuiContext& g = *GImGui;
6848
169k
    window->SkipRefresh = false;
6849
169k
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0)
6850
169k
        return;
6851
0
    if (g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_TryToAvoidRefresh)
6852
0
    {
6853
        // FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused.
6854
0
        if (window->Appearing) // If currently appearing
6855
0
            return;
6856
0
        if (window->Hidden) // If was hidden (previous frame)
6857
0
            return;
6858
0
        if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnHover) && g.HoveredWindow && window->RootWindow == g.HoveredWindow->RootWindow)
6859
0
            return;
6860
0
        if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnFocus) && g.NavWindow && window->RootWindow == g.NavWindow->RootWindow)
6861
0
            return;
6862
0
        window->DrawList = NULL;
6863
0
        window->SkipRefresh = true;
6864
0
    }
6865
0
}
6866
6867
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6868
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6869
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6870
// - WindowA            // FindBlockingModal() returns Modal1
6871
//   - WindowB          //                  .. returns Modal1
6872
//   - Modal1           //                  .. returns Modal2
6873
//      - WindowC       //                  .. returns Modal2
6874
//          - WindowD   //                  .. returns Modal2
6875
//          - Modal2    //                  .. returns Modal2
6876
//            - WindowE //                  .. returns NULL
6877
// Notes:
6878
// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6879
//   Only difference is here we check for ->Active/WasActive but it may be unnecessary.
6880
ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6881
55
{
6882
55
    ImGuiContext& g = *GImGui;
6883
55
    if (g.OpenPopupStack.Size <= 0)
6884
55
        return NULL;
6885
6886
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6887
0
    for (ImGuiPopupData& popup_data : g.OpenPopupStack)
6888
0
    {
6889
0
        ImGuiWindow* popup_window = popup_data.Window;
6890
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6891
0
            continue;
6892
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6893
0
            continue;
6894
0
        if (window == NULL)                                         // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6895
0
            return popup_window;
6896
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window may be over modal
6897
0
            continue;
6898
0
        return popup_window;                                        // Place window right below first block modal
6899
0
    }
6900
0
    return NULL;
6901
0
}
6902
6903
// Push a new Dear ImGui window to add widgets to.
6904
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6905
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6906
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6907
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6908
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6909
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6910
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6911
169k
{
6912
169k
    ImGuiContext& g = *GImGui;
6913
169k
    const ImGuiStyle& style = g.Style;
6914
169k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6915
169k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6916
169k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6917
6918
    // Find or create
6919
169k
    ImGuiWindow* window = FindWindowByName(name);
6920
169k
    const bool window_just_created = (window == NULL);
6921
169k
    if (window_just_created)
6922
3
        window = CreateNewWindow(name, flags);
6923
6924
    // [DEBUG] Debug break requested by user
6925
169k
    if (g.DebugBreakInWindow == window->ID)
6926
0
        IM_DEBUG_BREAK();
6927
6928
    // Automatically disable manual moving/resizing when NoInputs is set
6929
169k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6930
0
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6931
6932
169k
    const int current_frame = g.FrameCount;
6933
169k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6934
169k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6935
6936
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6937
169k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6938
169k
    if (flags & ImGuiWindowFlags_Popup)
6939
0
    {
6940
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6941
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6942
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6943
0
    }
6944
6945
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6946
169k
    const bool window_was_appearing = window->Appearing;
6947
169k
    if (first_begin_of_the_frame)
6948
169k
    {
6949
169k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6950
169k
        window->Appearing = window_just_activated_by_user;
6951
169k
        if (window->Appearing)
6952
3
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6953
169k
        window->FlagsPreviousFrame = window->Flags;
6954
169k
        window->Flags = (ImGuiWindowFlags)flags;
6955
169k
        window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
6956
169k
        window->LastFrameActive = current_frame;
6957
169k
        window->LastTimeActive = (float)g.Time;
6958
169k
        window->BeginOrderWithinParent = 0;
6959
169k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6960
169k
    }
6961
0
    else
6962
0
    {
6963
0
        flags = window->Flags;
6964
0
    }
6965
6966
    // Docking
6967
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6968
169k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6969
169k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6970
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6971
169k
    if (first_begin_of_the_frame)
6972
169k
    {
6973
169k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6974
169k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6975
169k
        bool dock_node_was_visible = window->DockNodeIsVisible;
6976
169k
        bool dock_tab_was_visible = window->DockTabIsVisible;
6977
169k
        if (has_dock_node || new_auto_dock_node)
6978
0
        {
6979
0
            BeginDocked(window, p_open);
6980
0
            flags = window->Flags;
6981
0
            if (window->DockIsActive)
6982
0
            {
6983
0
                IM_ASSERT(window->DockNode != NULL);
6984
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6985
0
            }
6986
6987
            // Amend the Appearing flag
6988
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6989
0
            {
6990
0
                window->Appearing = true;
6991
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6992
0
            }
6993
0
        }
6994
169k
        else
6995
169k
        {
6996
169k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6997
169k
        }
6998
169k
    }
6999
7000
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
7001
169k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
7002
169k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
7003
169k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
7004
7005
    // We allow window memory to be compacted so recreate the base stack when needed.
7006
169k
    if (window->IDStack.Size == 0)
7007
0
        window->IDStack.push_back(window->ID);
7008
7009
    // Add to stack
7010
169k
    g.CurrentWindow = window;
7011
169k
    ImGuiWindowStackData window_stack_data;
7012
169k
    window_stack_data.Window = window;
7013
169k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
7014
169k
    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
7015
169k
    window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled);
7016
169k
    g.CurrentWindowStack.push_back(window_stack_data);
7017
169k
    if (flags & ImGuiWindowFlags_ChildMenu)
7018
0
        g.BeginMenuDepth++;
7019
7020
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
7021
169k
    if (first_begin_of_the_frame)
7022
169k
    {
7023
169k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
7024
169k
        window->ParentWindowInBeginStack = parent_window_in_stack;
7025
7026
        // Focus route
7027
        // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
7028
        // Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
7029
169k
        window->ParentWindowForFocusRoute = (window->RootWindow != window) ? parent_window_in_stack : NULL;
7030
169k
        if (window->ParentWindowForFocusRoute == NULL && window->DockNode != NULL)
7031
0
            if (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockedWindowsInFocusRoute)
7032
0
                window->ParentWindowForFocusRoute = window->DockNode->HostWindow;
7033
7034
        // Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute()
7035
169k
        if (window->WindowClass.FocusRouteParentWindowId != 0)
7036
0
        {
7037
0
            window->ParentWindowForFocusRoute = FindWindowByID(window->WindowClass.FocusRouteParentWindowId);
7038
0
            IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId.
7039
0
        }
7040
169k
    }
7041
7042
    // Add to focus scope stack
7043
169k
    PushFocusScope((window->ChildFlags & ImGuiChildFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
7044
169k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
7045
7046
    // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
7047
169k
    if (flags & ImGuiWindowFlags_Popup)
7048
0
    {
7049
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7050
0
        popup_ref.Window = window;
7051
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
7052
0
        g.BeginPopupStack.push_back(popup_ref);
7053
0
        window->PopupId = popup_ref.PopupId;
7054
0
    }
7055
7056
    // Process SetNextWindow***() calls
7057
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
7058
169k
    bool window_pos_set_by_api = false;
7059
169k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
7060
169k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
7061
0
    {
7062
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
7063
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
7064
0
        {
7065
            // May be processed on the next frame if this is our first frame and we are measuring size
7066
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
7067
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
7068
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
7069
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7070
0
        }
7071
0
        else
7072
0
        {
7073
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
7074
0
        }
7075
0
    }
7076
169k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
7077
90.5k
    {
7078
90.5k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
7079
90.5k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
7080
90.5k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
7081
0
            g.NextWindowData.SizeVal.x = window->SizeFull.x;
7082
90.5k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
7083
0
            g.NextWindowData.SizeVal.y = window->SizeFull.y;
7084
90.5k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
7085
90.5k
    }
7086
169k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
7087
0
    {
7088
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
7089
0
        {
7090
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
7091
0
            window->ScrollTargetCenterRatio.x = 0.0f;
7092
0
        }
7093
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
7094
0
        {
7095
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
7096
0
            window->ScrollTargetCenterRatio.y = 0.0f;
7097
0
        }
7098
0
    }
7099
169k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
7100
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
7101
169k
    else if (first_begin_of_the_frame)
7102
169k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
7103
169k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
7104
0
        window->WindowClass = g.NextWindowData.WindowClass;
7105
169k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
7106
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
7107
169k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
7108
0
        FocusWindow(window);
7109
169k
    if (window->Appearing)
7110
3
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
7111
7112
    // [EXPERIMENTAL] Skip Refresh mode
7113
169k
    UpdateWindowSkipRefresh(window);
7114
7115
    // Nested root windows (typically tooltips) override disabled state
7116
169k
    if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7117
0
        BeginDisabledOverrideReenable();
7118
7119
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
7120
169k
    g.CurrentWindow = NULL;
7121
7122
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
7123
169k
    if (first_begin_of_the_frame && !window->SkipRefresh)
7124
169k
    {
7125
        // Initialize
7126
169k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
7127
169k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
7128
169k
        window->Active = true;
7129
169k
        window->HasCloseButton = (p_open != NULL);
7130
169k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
7131
169k
        window->IDStack.resize(1);
7132
169k
        window->DrawList->_ResetForNewFrame();
7133
169k
        window->DC.CurrentTableIdx = -1;
7134
169k
        if (flags & ImGuiWindowFlags_DockNodeHost)
7135
0
        {
7136
0
            window->DrawList->ChannelsSplit(2);
7137
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
7138
0
        }
7139
7140
        // Restore buffer capacity when woken from a compacted state, to avoid
7141
169k
        if (window->MemoryCompacted)
7142
0
            GcAwakeTransientWindowBuffers(window);
7143
7144
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
7145
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
7146
169k
        bool window_title_visible_elsewhere = false;
7147
169k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
7148
0
            window_title_visible_elsewhere = true;
7149
169k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
7150
0
            window_title_visible_elsewhere = true;
7151
169k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
7152
0
        {
7153
0
            size_t buf_len = (size_t)window->NameBufLen;
7154
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
7155
0
            window->NameBufLen = (int)buf_len;
7156
0
        }
7157
7158
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
7159
7160
        // Update contents size from last frame for auto-fitting (or use explicit size)
7161
169k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
7162
7163
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
7164
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
7165
        // it has a single usage before this code block and may be set below before it is finally checked.
7166
169k
        if (window->HiddenFramesCanSkipItems > 0)
7167
0
            window->HiddenFramesCanSkipItems--;
7168
169k
        if (window->HiddenFramesCannotSkipItems > 0)
7169
2
            window->HiddenFramesCannotSkipItems--;
7170
169k
        if (window->HiddenFramesForRenderOnly > 0)
7171
0
            window->HiddenFramesForRenderOnly--;
7172
7173
        // Hide new windows for one frame until they calculate their size
7174
169k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
7175
1
            window->HiddenFramesCannotSkipItems = 1;
7176
7177
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
7178
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
7179
169k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
7180
0
        {
7181
0
            window->HiddenFramesCannotSkipItems = 1;
7182
0
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
7183
0
            {
7184
0
                if (!window_size_x_set_by_api)
7185
0
                    window->Size.x = window->SizeFull.x = 0.f;
7186
0
                if (!window_size_y_set_by_api)
7187
0
                    window->Size.y = window->SizeFull.y = 0.f;
7188
0
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
7189
0
            }
7190
0
        }
7191
7192
        // SELECT VIEWPORT
7193
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
7194
7195
169k
        WindowSelectViewport(window);
7196
169k
        SetCurrentViewport(window, window->Viewport);
7197
169k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7198
169k
        SetCurrentWindow(window);
7199
169k
        flags = window->Flags;
7200
7201
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
7202
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
7203
7204
169k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
7205
11.4k
            window->WindowBorderSize = style.ChildBorderSize;
7206
158k
        else
7207
158k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
7208
169k
        window->WindowPadding = style.WindowPadding;
7209
169k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7210
5.27k
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7211
7212
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7213
169k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
7214
169k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7215
169k
        window->TitleBarHeight = (flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : g.FontSize + g.Style.FramePadding.y * 2.0f;
7216
169k
        window->MenuBarHeight = (flags & ImGuiWindowFlags_MenuBar) ? window->DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0f : 0.0f;
7217
7218
        // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
7219
        // Those flags will be altered further down in the function depending on more conditions.
7220
169k
        bool use_current_size_for_scrollbar_x = window_just_created;
7221
169k
        bool use_current_size_for_scrollbar_y = window_just_created;
7222
169k
        if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
7223
0
            use_current_size_for_scrollbar_x = true;
7224
169k
        if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
7225
0
            use_current_size_for_scrollbar_y = true;
7226
7227
        // Collapse window by double-clicking on title bar
7228
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
7229
169k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
7230
158k
        {
7231
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
7232
158k
            ImRect title_bar_rect = window->TitleBarRect();
7233
158k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max))
7234
138
                if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(ImGuiKey_MouseLeft) == ImGuiKeyOwner_NoOwner)
7235
0
                    window->WantCollapseToggle = true;
7236
158k
            if (window->WantCollapseToggle)
7237
1
            {
7238
1
                window->Collapsed = !window->Collapsed;
7239
1
                if (!window->Collapsed)
7240
0
                    use_current_size_for_scrollbar_y = true;
7241
1
                MarkIniSettingsDirty(window);
7242
1
            }
7243
158k
        }
7244
11.4k
        else
7245
11.4k
        {
7246
11.4k
            window->Collapsed = false;
7247
11.4k
        }
7248
169k
        window->WantCollapseToggle = false;
7249
7250
        // SIZE
7251
7252
        // Outer Decoration Sizes
7253
        // (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations).
7254
169k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7255
169k
        window->DecoOuterSizeX1 = 0.0f;
7256
169k
        window->DecoOuterSizeX2 = 0.0f;
7257
169k
        window->DecoOuterSizeY1 = window->TitleBarHeight + window->MenuBarHeight;
7258
169k
        window->DecoOuterSizeY2 = 0.0f;
7259
169k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7260
7261
        // Calculate auto-fit size, handle automatic resize
7262
169k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
7263
169k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7264
0
        {
7265
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7266
0
            if (!window_size_x_set_by_api)
7267
0
            {
7268
0
                window->SizeFull.x = size_auto_fit.x;
7269
0
                use_current_size_for_scrollbar_x = true;
7270
0
            }
7271
0
            if (!window_size_y_set_by_api)
7272
0
            {
7273
0
                window->SizeFull.y = size_auto_fit.y;
7274
0
                use_current_size_for_scrollbar_y = true;
7275
0
            }
7276
0
        }
7277
169k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7278
2
        {
7279
            // Auto-fit may only grow window during the first few frames
7280
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7281
2
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
7282
2
            {
7283
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
7284
2
                use_current_size_for_scrollbar_x = true;
7285
2
            }
7286
2
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
7287
2
            {
7288
2
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
7289
2
                use_current_size_for_scrollbar_y = true;
7290
2
            }
7291
2
            if (!window->Collapsed)
7292
2
                MarkIniSettingsDirty(window);
7293
2
        }
7294
7295
        // Apply minimum/maximum window size constraints and final size
7296
169k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
7297
169k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7298
7299
        // POSITION
7300
7301
        // Popup latch its initial position, will position itself when it appears next frame
7302
169k
        if (window_just_activated_by_user)
7303
3
        {
7304
3
            window->AutoPosLastDirection = ImGuiDir_None;
7305
3
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7306
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7307
3
        }
7308
7309
        // Position child window
7310
169k
        if (flags & ImGuiWindowFlags_ChildWindow)
7311
11.4k
        {
7312
11.4k
            IM_ASSERT(parent_window && parent_window->Active);
7313
11.4k
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7314
11.4k
            parent_window->DC.ChildWindows.push_back(window);
7315
11.4k
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7316
11.4k
                window->Pos = parent_window->DC.CursorPos;
7317
11.4k
        }
7318
7319
169k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7320
169k
        if (window_pos_with_pivot)
7321
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
7322
169k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7323
0
            window->Pos = FindBestWindowPosForPopup(window);
7324
169k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7325
0
            window->Pos = FindBestWindowPosForPopup(window);
7326
169k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7327
0
            window->Pos = FindBestWindowPosForPopup(window);
7328
7329
        // Late create viewport if we don't fit within our current host viewport.
7330
169k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
7331
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
7332
0
            {
7333
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
7334
                //ImGuiViewport* old_viewport = window->Viewport;
7335
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
7336
7337
                // FIXME-DPI
7338
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
7339
0
                SetCurrentViewport(window, window->Viewport);
7340
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7341
0
                SetCurrentWindow(window);
7342
0
            }
7343
7344
169k
        if (window->ViewportOwned)
7345
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
7346
7347
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7348
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7349
169k
        ImRect viewport_rect(window->Viewport->GetMainRect());
7350
169k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
7351
169k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
7352
169k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7353
7354
        // Clamp position/size so window stays visible within its viewport or monitor
7355
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7356
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
7357
169k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7358
158k
        {
7359
158k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
7360
158k
            {
7361
158k
                ClampWindowPos(window, visibility_rect);
7362
158k
            }
7363
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
7364
0
            {
7365
0
                if (g.MovingWindow != NULL && window->RootWindowDockTree == g.MovingWindow->RootWindowDockTree)
7366
0
                {
7367
                    // While moving windows we allow them to straddle monitors (#7299, #3071)
7368
0
                    visibility_rect = g.PlatformMonitorsFullWorkRect;
7369
0
                }
7370
0
                else
7371
0
                {
7372
                    // When not moving ensure visible in its monitor
7373
                    // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
7374
0
                    const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
7375
0
                    visibility_rect = ImRect(monitor->WorkPos, monitor->WorkPos + monitor->WorkSize);
7376
0
                }
7377
0
                visibility_rect.Expand(-visibility_padding);
7378
0
                ClampWindowPos(window, visibility_rect);
7379
0
            }
7380
158k
        }
7381
169k
        window->Pos = ImTrunc(window->Pos);
7382
7383
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7384
        // Large values tend to lead to variety of artifacts and are not recommended.
7385
169k
        if (window->ViewportOwned || window->DockIsActive)
7386
0
            window->WindowRounding = 0.0f;
7387
169k
        else
7388
169k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7389
7390
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7391
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7392
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7393
7394
        // Apply window focus (new and reactivated windows are moved to front)
7395
169k
        bool want_focus = false;
7396
169k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7397
3
        {
7398
3
            if (flags & ImGuiWindowFlags_Popup)
7399
0
                want_focus = true;
7400
3
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
7401
2
                want_focus = true;
7402
3
        }
7403
7404
        // [Test Engine] Register whole window in the item system (before submitting further decorations)
7405
#ifdef IMGUI_ENABLE_TEST_ENGINE
7406
        if (g.TestEngineHookItems)
7407
        {
7408
            IM_ASSERT(window->IDStack.Size == 1);
7409
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7410
            IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7411
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7412
            window->IDStack.Size = 1;
7413
        }
7414
#endif
7415
7416
        // Decide if we are going to handle borders and resize grips
7417
169k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
7418
7419
        // Handle manual resize: Resize Grips, Borders, Gamepad
7420
169k
        int border_hovered = -1, border_held = -1;
7421
169k
        ImU32 resize_grip_col[4] = {};
7422
169k
        const int resize_grip_count = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
7423
169k
        const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7424
169k
        if (handle_borders_and_resize_grips && !window->Collapsed)
7425
102k
            if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7426
0
            {
7427
0
                if (auto_fit_mask & (1 << ImGuiAxis_X))
7428
0
                    use_current_size_for_scrollbar_x = true;
7429
0
                if (auto_fit_mask & (1 << ImGuiAxis_Y))
7430
0
                    use_current_size_for_scrollbar_y = true;
7431
0
            }
7432
169k
        window->ResizeBorderHovered = (signed char)border_hovered;
7433
169k
        window->ResizeBorderHeld = (signed char)border_held;
7434
7435
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
7436
169k
        if (window->ViewportOwned)
7437
0
        {
7438
0
            if (!window->Viewport->PlatformRequestMove)
7439
0
                window->Viewport->Pos = window->Pos;
7440
0
            if (!window->Viewport->PlatformRequestResize)
7441
0
                window->Viewport->Size = window->Size;
7442
0
            window->Viewport->UpdateWorkRect();
7443
0
            viewport_rect = window->Viewport->GetMainRect();
7444
0
        }
7445
7446
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
7447
169k
        window->ViewportPos = window->Viewport->Pos;
7448
7449
        // SCROLLBAR VISIBILITY
7450
7451
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7452
169k
        if (!window->Collapsed)
7453
102k
        {
7454
            // When reading the current size we need to read it after size constraints have been applied.
7455
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7456
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7457
102k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7458
102k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7459
102k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7460
102k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7461
102k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7462
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7463
102k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7464
102k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
7465
102k
            if (window->ScrollbarX && !window->ScrollbarY)
7466
3.01k
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
7467
102k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7468
7469
            // Amend the partially filled window->DecorationXXX values.
7470
102k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7471
102k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7472
102k
        }
7473
7474
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7475
        // Update various regions. Variables they depend on should be set above in this function.
7476
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7477
7478
        // Outer rectangle
7479
        // Not affected by window border size. Used by:
7480
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7481
        // - Begin() initial clipping rect for drawing window background and borders.
7482
        // - Begin() clipping whole child
7483
169k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7484
169k
        const ImRect outer_rect = window->Rect();
7485
169k
        const ImRect title_bar_rect = window->TitleBarRect();
7486
169k
        window->OuterRectClipped = outer_rect;
7487
169k
        if (window->DockIsActive)
7488
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight;
7489
169k
        window->OuterRectClipped.ClipWith(host_rect);
7490
7491
        // Inner rectangle
7492
        // Not affected by window border size. Used by:
7493
        // - InnerClipRect
7494
        // - ScrollToRectEx()
7495
        // - NavUpdatePageUpPageDown()
7496
        // - Scrollbar()
7497
169k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7498
169k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7499
169k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7500
169k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7501
7502
        // Inner clipping rectangle.
7503
        // - Extend a outside of normal work region up to borders.
7504
        // - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7505
        // - It also makes clipped items be more noticeable.
7506
        // - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5f on left and right edge), see #3312
7507
        // - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7508
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7509
        // Affected by window/frame border size. Used by:
7510
        // - Begin() initial clip rect
7511
169k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7512
169k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + window->WindowBorderSize);
7513
169k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7514
169k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - window->WindowBorderSize);
7515
169k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7516
169k
        window->InnerClipRect.ClipWithFull(host_rect);
7517
7518
        // Default item width. Make it proportional to window size if window manually resizes
7519
169k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7520
169k
            window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
7521
6
        else
7522
6
            window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
7523
7524
        // SCROLLING
7525
7526
        // Lock down maximum scrolling
7527
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7528
        // for right/bottom aligned items without creating a scrollbar.
7529
169k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7530
169k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7531
7532
        // Apply scrolling
7533
169k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7534
169k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7535
169k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7536
7537
        // DRAWING
7538
7539
        // Setup draw list and outer clipping rectangle
7540
169k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7541
169k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7542
169k
        PushClipRect(host_rect.Min, host_rect.Max, false);
7543
7544
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7545
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7546
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7547
169k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7548
169k
        if (is_undocked_or_docked_visible)
7549
169k
        {
7550
169k
            bool render_decorations_in_parent = false;
7551
169k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7552
11.4k
            {
7553
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7554
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7555
11.4k
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7556
11.4k
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7557
11.4k
                bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7558
11.4k
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7559
11.4k
                    render_decorations_in_parent = true;
7560
11.4k
            }
7561
169k
            if (render_decorations_in_parent)
7562
11.4k
                window->DrawList = parent_window->DrawList;
7563
7564
            // Handle title bar, scrollbar, resize grips and resize borders
7565
169k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7566
169k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7567
169k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7568
7569
169k
            if (render_decorations_in_parent)
7570
11.4k
                window->DrawList = &window->DrawListInst;
7571
169k
        }
7572
7573
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7574
7575
        // Work rectangle.
7576
        // Affected by window padding and border size. Used by:
7577
        // - Columns() for right-most edge
7578
        // - TreeNode(), CollapsingHeader() for right-most edge
7579
        // - BeginTabBar() for right-most edge
7580
169k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7581
169k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7582
169k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7583
169k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7584
169k
        window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7585
169k
        window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7586
169k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7587
169k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7588
169k
        window->ParentWorkRect = window->WorkRect;
7589
7590
        // [LEGACY] Content Region
7591
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7592
        // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
7593
        // Used by:
7594
        // - Mouse wheel scrolling + many other things
7595
169k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7596
169k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7597
169k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7598
169k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7599
7600
        // Setup drawing context
7601
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7602
169k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7603
169k
        window->DC.GroupOffset.x = 0.0f;
7604
169k
        window->DC.ColumnsOffset.x = 0.0f;
7605
7606
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7607
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7608
169k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7609
169k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7610
169k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7611
169k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7612
169k
        window->DC.CursorPos = window->DC.CursorStartPos;
7613
169k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7614
169k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7615
169k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7616
169k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7617
169k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7618
169k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7619
7620
169k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7621
169k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7622
169k
        window->DC.NavLayersActiveMaskNext = 0x00;
7623
169k
        window->DC.NavIsScrollPushableX = true;
7624
169k
        window->DC.NavHideHighlightOneFrame = false;
7625
169k
        window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7626
7627
169k
        window->DC.MenuBarAppending = false;
7628
169k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7629
169k
        window->DC.TreeDepth = 0;
7630
169k
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7631
169k
        window->DC.ChildWindows.resize(0);
7632
169k
        window->DC.StateStorage = &window->StateStorage;
7633
169k
        window->DC.CurrentColumns = NULL;
7634
169k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7635
169k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7636
7637
169k
        window->DC.ItemWidth = window->ItemWidthDefault;
7638
169k
        window->DC.TextWrapPos = -1.0f; // disabled
7639
169k
        window->DC.ItemWidthStack.resize(0);
7640
169k
        window->DC.TextWrapPosStack.resize(0);
7641
169k
        if (flags & ImGuiWindowFlags_Modal)
7642
0
            window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(GetStyleColorVec4(ImGuiCol_ModalWindowDimBg));
7643
7644
169k
        if (window->AutoFitFramesX > 0)
7645
2
            window->AutoFitFramesX--;
7646
169k
        if (window->AutoFitFramesY > 0)
7647
2
            window->AutoFitFramesY--;
7648
7649
        // Clear SetNextWindowXXX data (can aim to move this higher in the function)
7650
169k
        g.NextWindowData.ClearFlags();
7651
7652
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7653
        // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7654
        // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7655
        // - Position window behind the modal that is not a begin-parent of this window.
7656
169k
        if (want_focus)
7657
2
            FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7658
169k
        if (want_focus && window == g.NavWindow)
7659
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7660
7661
        // Close requested by platform window (apply to all windows in this viewport)
7662
169k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7663
0
        {
7664
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
7665
0
            *p_open = false;
7666
0
            g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
7667
0
        }
7668
7669
        // Title bar
7670
169k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7671
158k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7672
7673
        // Clear hit test shape every frame
7674
169k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7675
7676
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7677
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7678
        // Maybe we can support CTRL+C on every element?
7679
        /*
7680
        //if (g.NavWindow == window && g.ActiveId == 0)
7681
        if (g.ActiveId == window->MoveId)
7682
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7683
                LogToClipboard();
7684
        */
7685
7686
169k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7687
169k
        {
7688
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7689
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7690
169k
            if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7691
55
                BeginDockableDragDropSource(window);
7692
7693
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7694
169k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7695
38
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7696
22
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7697
22
                        BeginDockableDragDropTarget(window);
7698
169k
        }
7699
7700
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7701
        // This is useful to allow creating context menus on title bar only, etc.
7702
169k
        SetLastItemDataForWindow(window, title_bar_rect);
7703
7704
        // [DEBUG]
7705
169k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7706
169k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7707
0
            DebugLocateItemResolveWithLastItem();
7708
169k
#endif
7709
7710
        // [Test Engine] Register title bar / tab with MoveId.
7711
#ifdef IMGUI_ENABLE_TEST_ENGINE
7712
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7713
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7714
#endif
7715
169k
    }
7716
0
    else
7717
0
    {
7718
        // Skip refresh always mark active
7719
0
        if (window->SkipRefresh)
7720
0
            window->Active = true;
7721
7722
        // Append
7723
0
        SetCurrentViewport(window, window->Viewport);
7724
0
        SetCurrentWindow(window);
7725
0
        g.NextWindowData.ClearFlags();
7726
0
        SetLastItemDataForWindow(window, window->TitleBarRect());
7727
0
    }
7728
7729
169k
    if (!(flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh)
7730
169k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7731
7732
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7733
169k
    window->WriteAccessed = false;
7734
169k
    window->BeginCount++;
7735
7736
    // Update visibility
7737
169k
    if (first_begin_of_the_frame && !window->SkipRefresh)
7738
169k
    {
7739
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7740
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7741
        // This is analogous to regular windows being hidden from one frame.
7742
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7743
169k
        if (window->DockIsActive && !window->DockTabIsVisible)
7744
0
        {
7745
0
            if (window->LastFrameJustFocused == g.FrameCount)
7746
0
                window->HiddenFramesCannotSkipItems = 1;
7747
0
            else
7748
0
                window->HiddenFramesCanSkipItems = 1;
7749
0
        }
7750
7751
169k
        if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
7752
11.4k
        {
7753
            // Child window can be out of sight and have "negative" clip windows.
7754
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7755
11.4k
            IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
7756
11.4k
            const bool nav_request = (window->ChildFlags & ImGuiChildFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7757
11.4k
            if (!g.LogEnabled && !nav_request)
7758
11.4k
                if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7759
0
                {
7760
0
                    if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7761
0
                        window->HiddenFramesCannotSkipItems = 1;
7762
0
                    else
7763
0
                        window->HiddenFramesCanSkipItems = 1;
7764
0
                }
7765
7766
            // Hide along with parent or if parent is collapsed
7767
11.4k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7768
0
                window->HiddenFramesCanSkipItems = 1;
7769
11.4k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7770
1
                window->HiddenFramesCannotSkipItems = 1;
7771
11.4k
        }
7772
7773
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7774
169k
        if (style.Alpha <= 0.0f)
7775
0
            window->HiddenFramesCanSkipItems = 1;
7776
7777
        // Update the Hidden flag
7778
169k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7779
169k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7780
7781
        // Disable inputs for requested number of frames
7782
169k
        if (window->DisableInputsFrames > 0)
7783
0
        {
7784
0
            window->DisableInputsFrames--;
7785
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7786
0
        }
7787
7788
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7789
169k
        bool skip_items = false;
7790
169k
        if (window->Collapsed || !window->Active || hidden_regular)
7791
67.6k
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7792
67.6k
                skip_items = true;
7793
169k
        window->SkipItems = skip_items;
7794
7795
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7796
169k
        if (window->SkipItems)
7797
67.6k
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7798
7799
        // Sanity check: there are two spots which can set Appearing = true
7800
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7801
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7802
169k
        if (window->SkipItems && !window->Appearing)
7803
169k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7804
169k
    }
7805
0
    else if (first_begin_of_the_frame)
7806
0
    {
7807
        // Skip refresh mode
7808
0
        window->SkipItems = true;
7809
0
    }
7810
7811
    // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7812
    // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7813
169k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7814
169k
    if (!window->IsFallbackWindow)
7815
90.5k
        if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
7816
0
        {
7817
0
            if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7818
0
            if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7819
0
            return false;
7820
0
        }
7821
169k
#endif
7822
7823
169k
    return !window->SkipItems;
7824
169k
}
7825
7826
static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect)
7827
169k
{
7828
169k
    ImGuiContext& g = *GImGui;
7829
169k
    if (window->DockIsActive)
7830
0
        SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7831
169k
    else
7832
169k
        SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(rect.Min, rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, rect);
7833
169k
}
7834
7835
void ImGui::End()
7836
169k
{
7837
169k
    ImGuiContext& g = *GImGui;
7838
169k
    ImGuiWindow* window = g.CurrentWindow;
7839
7840
    // Error checking: verify that user hasn't called End() too many times!
7841
169k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7842
0
    {
7843
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7844
0
        return;
7845
0
    }
7846
169k
    ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
7847
7848
    // Error checking: verify that user doesn't directly call End() on a child window.
7849
169k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7850
169k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7851
7852
    // Close anything that is open
7853
169k
    if (window->DC.CurrentColumns)
7854
0
        EndColumns();
7855
169k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh)   // Pop inner window clip rectangle
7856
169k
        PopClipRect();
7857
169k
    PopFocusScope();
7858
169k
    if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7859
0
        EndDisabledOverrideReenable();
7860
7861
169k
    if (window->SkipRefresh)
7862
0
    {
7863
0
        IM_ASSERT(window->DrawList == NULL);
7864
0
        window->DrawList = &window->DrawListInst;
7865
0
    }
7866
7867
    // Stop logging
7868
169k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7869
158k
        LogFinish();
7870
7871
169k
    if (window->DC.IsSetPos)
7872
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7873
7874
    // Docking: report contents sizes to parent to allow for auto-resize
7875
169k
    if (window->DockNode && window->DockTabIsVisible)
7876
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7877
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7878
7879
    // Pop from window stack
7880
169k
    g.LastItemData = window_stack_data.ParentLastItemDataBackup;
7881
169k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7882
0
        g.BeginMenuDepth--;
7883
169k
    if (window->Flags & ImGuiWindowFlags_Popup)
7884
0
        g.BeginPopupStack.pop_back();
7885
169k
    window_stack_data.StackSizesOnBegin.CompareWithContextState(&g);
7886
169k
    g.CurrentWindowStack.pop_back();
7887
169k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7888
169k
    if (g.CurrentWindow)
7889
90.5k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7890
169k
}
7891
7892
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7893
3.26k
{
7894
3.26k
    ImGuiContext& g = *GImGui;
7895
3.26k
    IM_ASSERT(window == window->RootWindow);
7896
7897
3.26k
    const int cur_order = window->FocusOrder;
7898
3.26k
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7899
3.26k
    if (g.WindowsFocusOrder.back() == window)
7900
3.26k
        return;
7901
7902
0
    const int new_order = g.WindowsFocusOrder.Size - 1;
7903
0
    for (int n = cur_order; n < new_order; n++)
7904
0
    {
7905
0
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7906
0
        g.WindowsFocusOrder[n]->FocusOrder--;
7907
0
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7908
0
    }
7909
0
    g.WindowsFocusOrder[new_order] = window;
7910
0
    window->FocusOrder = (short)new_order;
7911
0
}
7912
7913
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7914
3.26k
{
7915
3.26k
    ImGuiContext& g = *GImGui;
7916
3.26k
    ImGuiWindow* current_front_window = g.Windows.back();
7917
3.26k
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7918
3.26k
        return;
7919
0
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7920
0
        if (g.Windows[i] == window)
7921
0
        {
7922
0
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7923
0
            g.Windows[g.Windows.Size - 1] = window;
7924
0
            break;
7925
0
        }
7926
0
}
7927
7928
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7929
0
{
7930
0
    ImGuiContext& g = *GImGui;
7931
0
    if (g.Windows[0] == window)
7932
0
        return;
7933
0
    for (int i = 0; i < g.Windows.Size; i++)
7934
0
        if (g.Windows[i] == window)
7935
0
        {
7936
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7937
0
            g.Windows[0] = window;
7938
0
            break;
7939
0
        }
7940
0
}
7941
7942
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7943
0
{
7944
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7945
0
    ImGuiContext& g = *GImGui;
7946
0
    window = window->RootWindow;
7947
0
    behind_window = behind_window->RootWindow;
7948
0
    int pos_wnd = FindWindowDisplayIndex(window);
7949
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7950
0
    if (pos_wnd < pos_beh)
7951
0
    {
7952
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7953
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7954
0
        g.Windows[pos_beh - 1] = window;
7955
0
    }
7956
0
    else
7957
0
    {
7958
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7959
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7960
0
        g.Windows[pos_beh] = window;
7961
0
    }
7962
0
}
7963
7964
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7965
0
{
7966
0
    ImGuiContext& g = *GImGui;
7967
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
7968
0
}
7969
7970
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7971
void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
7972
13.0k
{
7973
13.0k
    ImGuiContext& g = *GImGui;
7974
7975
    // Modal check?
7976
13.0k
    if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
7977
55
        if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
7978
0
        {
7979
            // This block would typically be reached in two situations:
7980
            // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag.
7981
            // - User clicking on void or anything behind a modal while a modal is open (window == NULL)
7982
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
7983
0
            if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7984
0
                BringWindowToDisplayBehind(window, blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?)
7985
0
            ClosePopupsOverWindow(GetTopMostPopupModal(), false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals
7986
0
            return;
7987
0
        }
7988
7989
    // Find last focused child (if any) and focus it instead.
7990
13.0k
    if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
7991
0
        window = NavRestoreLastChildNavWindow(window);
7992
7993
    // Apply focus
7994
13.0k
    if (g.NavWindow != window)
7995
4.65k
    {
7996
4.65k
        SetNavWindow(window);
7997
4.65k
        if (window && g.NavDisableMouseHover)
7998
365
            g.NavMousePosDirty = true;
7999
4.65k
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
8000
4.65k
        g.NavLayer = ImGuiNavLayer_Main;
8001
4.65k
        SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
8002
4.65k
        g.NavIdIsAlive = false;
8003
4.65k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
8004
8005
        // Close popups if any
8006
4.65k
        ClosePopupsOverWindow(window, false);
8007
4.65k
    }
8008
8009
    // Move the root window to the top of the pile
8010
13.0k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
8011
13.0k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
8012
13.0k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
8013
13.0k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
8014
13.0k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
8015
8016
    // Steal active widgets. Some of the cases it triggers includes:
8017
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
8018
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
8019
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
8020
13.0k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
8021
87
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
8022
12
            ClearActiveID();
8023
8024
    // Passing NULL allow to disable keyboard focus
8025
13.0k
    if (!window)
8026
9.78k
        return;
8027
3.26k
    window->LastFrameJustFocused = g.FrameCount;
8028
8029
    // Select in dock node
8030
    // For #2304 we avoid applying focus immediately before the tabbar is visible.
8031
    //if (dock_node && dock_node->TabBar)
8032
    //    dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
8033
8034
    // Bring to front
8035
3.26k
    BringWindowToFocusFront(focus_front_window);
8036
3.26k
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
8037
3.26k
        BringWindowToDisplayFront(display_front_window);
8038
3.26k
}
8039
8040
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
8041
0
{
8042
0
    ImGuiContext& g = *GImGui;
8043
0
    int start_idx = g.WindowsFocusOrder.Size - 1;
8044
0
    if (under_this_window != NULL)
8045
0
    {
8046
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
8047
0
        int offset = -1;
8048
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
8049
0
        {
8050
0
            under_this_window = under_this_window->ParentWindow;
8051
0
            offset = 0;
8052
0
        }
8053
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
8054
0
    }
8055
0
    for (int i = start_idx; i >= 0; i--)
8056
0
    {
8057
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
8058
0
        ImGuiWindow* window = g.WindowsFocusOrder[i];
8059
0
        if (window == ignore_window || !window->WasActive)
8060
0
            continue;
8061
0
        if (filter_viewport != NULL && window->Viewport != filter_viewport)
8062
0
            continue;
8063
0
        if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
8064
0
        {
8065
            // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
8066
            // This is failing (lagging by one frame) for docked windows.
8067
            // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
8068
            // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
8069
            // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
8070
0
            FocusWindow(window, flags);
8071
0
            return;
8072
0
        }
8073
0
    }
8074
0
    FocusWindow(NULL, flags);
8075
0
}
8076
8077
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
8078
void ImGui::SetCurrentFont(ImFont* font)
8079
79.1k
{
8080
79.1k
    ImGuiContext& g = *GImGui;
8081
79.1k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
8082
79.1k
    IM_ASSERT(font->Scale > 0.0f);
8083
79.1k
    g.Font = font;
8084
79.1k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
8085
79.1k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
8086
79.1k
    g.FontScale = g.FontSize / g.Font->FontSize;
8087
8088
79.1k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
8089
79.1k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
8090
79.1k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
8091
79.1k
    g.DrawListSharedData.Font = g.Font;
8092
79.1k
    g.DrawListSharedData.FontSize = g.FontSize;
8093
79.1k
    g.DrawListSharedData.FontScale = g.FontScale;
8094
79.1k
}
8095
8096
void ImGui::PushFont(ImFont* font)
8097
0
{
8098
0
    ImGuiContext& g = *GImGui;
8099
0
    if (!font)
8100
0
        font = GetDefaultFont();
8101
0
    SetCurrentFont(font);
8102
0
    g.FontStack.push_back(font);
8103
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
8104
0
}
8105
8106
void  ImGui::PopFont()
8107
0
{
8108
0
    ImGuiContext& g = *GImGui;
8109
0
    g.CurrentWindow->DrawList->PopTextureID();
8110
0
    g.FontStack.pop_back();
8111
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
8112
0
}
8113
8114
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
8115
11.4k
{
8116
11.4k
    ImGuiContext& g = *GImGui;
8117
11.4k
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
8118
11.4k
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
8119
11.4k
    if (enabled)
8120
0
        item_flags |= option;
8121
11.4k
    else
8122
11.4k
        item_flags &= ~option;
8123
11.4k
    g.CurrentItemFlags = item_flags;
8124
11.4k
    g.ItemFlagsStack.push_back(item_flags);
8125
11.4k
}
8126
8127
void ImGui::PopItemFlag()
8128
11.4k
{
8129
11.4k
    ImGuiContext& g = *GImGui;
8130
11.4k
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
8131
11.4k
    g.ItemFlagsStack.pop_back();
8132
11.4k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
8133
11.4k
}
8134
8135
// BeginDisabled()/EndDisabled()
8136
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
8137
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
8138
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
8139
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
8140
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
8141
void ImGui::BeginDisabled(bool disabled)
8142
0
{
8143
0
    ImGuiContext& g = *GImGui;
8144
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8145
0
    if (!was_disabled && disabled)
8146
0
    {
8147
0
        g.DisabledAlphaBackup = g.Style.Alpha;
8148
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
8149
0
    }
8150
0
    if (was_disabled || disabled)
8151
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
8152
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags); // FIXME-OPT: can we simply skip this and use DisabledStackSize?
8153
0
    g.DisabledStackSize++;
8154
0
}
8155
8156
void ImGui::EndDisabled()
8157
0
{
8158
0
    ImGuiContext& g = *GImGui;
8159
0
    IM_ASSERT(g.DisabledStackSize > 0);
8160
0
    g.DisabledStackSize--;
8161
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8162
    //PopItemFlag();
8163
0
    g.ItemFlagsStack.pop_back();
8164
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
8165
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
8166
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
8167
0
}
8168
8169
// Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name.
8170
// Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal.
8171
// The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled().
8172
void ImGui::BeginDisabledOverrideReenable()
8173
0
{
8174
0
    ImGuiContext& g = *GImGui;
8175
0
    IM_ASSERT(g.CurrentItemFlags & ImGuiItemFlags_Disabled);
8176
0
    g.Style.Alpha = g.DisabledAlphaBackup;
8177
0
    g.CurrentItemFlags &= ~ImGuiItemFlags_Disabled;
8178
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
8179
0
    g.DisabledStackSize++;
8180
0
}
8181
8182
void ImGui::EndDisabledOverrideReenable()
8183
0
{
8184
0
    ImGuiContext& g = *GImGui;
8185
0
    g.DisabledStackSize--;
8186
0
    IM_ASSERT(g.DisabledStackSize > 0);
8187
0
    g.ItemFlagsStack.pop_back();
8188
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
8189
0
    g.Style.Alpha = g.DisabledAlphaBackup * g.Style.DisabledAlpha;
8190
0
}
8191
8192
void ImGui::PushTabStop(bool tab_stop)
8193
11.4k
{
8194
11.4k
    PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);
8195
11.4k
}
8196
8197
void ImGui::PopTabStop()
8198
11.4k
{
8199
11.4k
    PopItemFlag();
8200
11.4k
}
8201
8202
void ImGui::PushButtonRepeat(bool repeat)
8203
0
{
8204
0
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
8205
0
}
8206
8207
void ImGui::PopButtonRepeat()
8208
0
{
8209
0
    PopItemFlag();
8210
0
}
8211
8212
void ImGui::PushTextWrapPos(float wrap_pos_x)
8213
0
{
8214
0
    ImGuiWindow* window = GetCurrentWindow();
8215
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
8216
0
    window->DC.TextWrapPos = wrap_pos_x;
8217
0
}
8218
8219
void ImGui::PopTextWrapPos()
8220
0
{
8221
0
    ImGuiWindow* window = GetCurrentWindow();
8222
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
8223
0
    window->DC.TextWrapPosStack.pop_back();
8224
0
}
8225
8226
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
8227
0
{
8228
0
    ImGuiWindow* last_window = NULL;
8229
0
    while (last_window != window)
8230
0
    {
8231
0
        last_window = window;
8232
0
        window = window->RootWindow;
8233
0
        if (popup_hierarchy)
8234
0
            window = window->RootWindowPopupTree;
8235
0
    if (dock_hierarchy)
8236
0
      window = window->RootWindowDockTree;
8237
0
  }
8238
0
    return window;
8239
0
}
8240
8241
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
8242
0
{
8243
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
8244
0
    if (window_root == potential_parent)
8245
0
        return true;
8246
0
    while (window != NULL)
8247
0
    {
8248
0
        if (window == potential_parent)
8249
0
            return true;
8250
0
        if (window == window_root) // end of chain
8251
0
            return false;
8252
0
        window = window->ParentWindow;
8253
0
    }
8254
0
    return false;
8255
0
}
8256
8257
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
8258
0
{
8259
0
    if (window->RootWindow == potential_parent)
8260
0
        return true;
8261
0
    while (window != NULL)
8262
0
    {
8263
0
        if (window == potential_parent)
8264
0
            return true;
8265
0
        window = window->ParentWindowInBeginStack;
8266
0
    }
8267
0
    return false;
8268
0
}
8269
8270
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
8271
0
{
8272
0
    ImGuiContext& g = *GImGui;
8273
8274
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
8275
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
8276
0
    if (display_layer_delta != 0)
8277
0
        return display_layer_delta > 0;
8278
8279
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
8280
0
    {
8281
0
        ImGuiWindow* candidate_window = g.Windows[i];
8282
0
        if (candidate_window == potential_above)
8283
0
            return true;
8284
0
        if (candidate_window == potential_below)
8285
0
            return false;
8286
0
    }
8287
0
    return false;
8288
0
}
8289
8290
// Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
8291
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
8292
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
8293
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
8294
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
8295
15.0k
{
8296
15.0k
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
8297
8298
15.0k
    ImGuiContext& g = *GImGui;
8299
15.0k
    ImGuiWindow* ref_window = g.HoveredWindow;
8300
15.0k
    ImGuiWindow* cur_window = g.CurrentWindow;
8301
15.0k
    if (ref_window == NULL)
8302
14.6k
        return false;
8303
8304
409
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8305
409
    {
8306
409
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
8307
409
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8308
409
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
8309
409
        if (flags & ImGuiHoveredFlags_RootWindow)
8310
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8311
8312
409
        bool result;
8313
409
        if (flags & ImGuiHoveredFlags_ChildWindows)
8314
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8315
409
        else
8316
409
            result = (ref_window == cur_window);
8317
409
        if (!result)
8318
406
            return false;
8319
409
    }
8320
8321
3
    if (!IsWindowContentHoverable(ref_window, flags))
8322
0
        return false;
8323
3
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8324
3
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8325
0
            return false;
8326
8327
    // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8328
    // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8329
    // to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true
8330
    // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8331
    // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8332
3
    if (flags & ImGuiHoveredFlags_ForTooltip)
8333
0
        flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
8334
3
    if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8335
0
        return false;
8336
8337
3
    return true;
8338
3
}
8339
8340
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
8341
22.8k
{
8342
22.8k
    ImGuiContext& g = *GImGui;
8343
22.8k
    ImGuiWindow* ref_window = g.NavWindow;
8344
22.8k
    ImGuiWindow* cur_window = g.CurrentWindow;
8345
8346
22.8k
    if (ref_window == NULL)
8347
15.1k
        return false;
8348
7.70k
    if (flags & ImGuiFocusedFlags_AnyWindow)
8349
0
        return true;
8350
8351
7.70k
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
8352
7.70k
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
8353
7.70k
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
8354
7.70k
    if (flags & ImGuiHoveredFlags_RootWindow)
8355
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8356
8357
7.70k
    if (flags & ImGuiHoveredFlags_ChildWindows)
8358
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8359
7.70k
    else
8360
7.70k
        return (ref_window == cur_window);
8361
7.70k
}
8362
8363
ImGuiID ImGui::GetWindowDockID()
8364
0
{
8365
0
    ImGuiContext& g = *GImGui;
8366
0
    return g.CurrentWindow->DockId;
8367
0
}
8368
8369
bool ImGui::IsWindowDocked()
8370
0
{
8371
0
    ImGuiContext& g = *GImGui;
8372
0
    return g.CurrentWindow->DockIsActive;
8373
0
}
8374
8375
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
8376
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
8377
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
8378
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
8379
0
{
8380
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
8381
0
}
8382
8383
float ImGui::GetWindowWidth()
8384
3.06k
{
8385
3.06k
    ImGuiWindow* window = GImGui->CurrentWindow;
8386
3.06k
    return window->Size.x;
8387
3.06k
}
8388
8389
float ImGui::GetWindowHeight()
8390
3.07k
{
8391
3.07k
    ImGuiWindow* window = GImGui->CurrentWindow;
8392
3.07k
    return window->Size.y;
8393
3.07k
}
8394
8395
ImVec2 ImGui::GetWindowPos()
8396
0
{
8397
0
    ImGuiContext& g = *GImGui;
8398
0
    ImGuiWindow* window = g.CurrentWindow;
8399
0
    return window->Pos;
8400
0
}
8401
8402
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8403
8
{
8404
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8405
8
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8406
0
        return;
8407
8408
8
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8409
8
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8410
8
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8411
8412
    // Set
8413
8
    const ImVec2 old_pos = window->Pos;
8414
8
    window->Pos = ImTrunc(pos);
8415
8
    ImVec2 offset = window->Pos - old_pos;
8416
8
    if (offset.x == 0.0f && offset.y == 0.0f)
8417
0
        return;
8418
8
    MarkIniSettingsDirty(window);
8419
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8420
8
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
8421
8
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8422
8
    window->DC.IdealMaxPos += offset;
8423
8
    window->DC.CursorStartPos += offset;
8424
8
}
8425
8426
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8427
0
{
8428
0
    ImGuiWindow* window = GetCurrentWindowRead();
8429
0
    SetWindowPos(window, pos, cond);
8430
0
}
8431
8432
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8433
0
{
8434
0
    if (ImGuiWindow* window = FindWindowByName(name))
8435
0
        SetWindowPos(window, pos, cond);
8436
0
}
8437
8438
ImVec2 ImGui::GetWindowSize()
8439
0
{
8440
0
    ImGuiWindow* window = GetCurrentWindowRead();
8441
0
    return window->Size;
8442
0
}
8443
8444
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8445
90.5k
{
8446
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8447
90.5k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8448
79.1k
        return;
8449
8450
11.4k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8451
11.4k
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8452
8453
    // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8454
11.4k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8455
2
        window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8456
11.4k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8457
2
        window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8458
8459
    // Set
8460
11.4k
    ImVec2 old_size = window->SizeFull;
8461
11.4k
    if (size.x <= 0.0f)
8462
0
        window->AutoFitOnlyGrows = false;
8463
11.4k
    else
8464
11.4k
        window->SizeFull.x = IM_TRUNC(size.x);
8465
11.4k
    if (size.y <= 0.0f)
8466
0
        window->AutoFitOnlyGrows = false;
8467
11.4k
    else
8468
11.4k
        window->SizeFull.y = IM_TRUNC(size.y);
8469
11.4k
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8470
11.3k
        MarkIniSettingsDirty(window);
8471
11.4k
}
8472
8473
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8474
0
{
8475
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
8476
0
}
8477
8478
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8479
0
{
8480
0
    if (ImGuiWindow* window = FindWindowByName(name))
8481
0
        SetWindowSize(window, size, cond);
8482
0
}
8483
8484
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8485
0
{
8486
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8487
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8488
0
        return;
8489
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8490
8491
    // Set
8492
0
    window->Collapsed = collapsed;
8493
0
}
8494
8495
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8496
0
{
8497
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
8498
0
    window->HitTestHoleSize = ImVec2ih(size);
8499
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8500
0
}
8501
8502
void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8503
0
{
8504
0
    window->Hidden = window->SkipItems = true;
8505
0
    window->HiddenFramesCanSkipItems = 1;
8506
0
}
8507
8508
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8509
0
{
8510
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8511
0
}
8512
8513
bool ImGui::IsWindowCollapsed()
8514
0
{
8515
0
    ImGuiWindow* window = GetCurrentWindowRead();
8516
0
    return window->Collapsed;
8517
0
}
8518
8519
bool ImGui::IsWindowAppearing()
8520
0
{
8521
0
    ImGuiWindow* window = GetCurrentWindowRead();
8522
0
    return window->Appearing;
8523
0
}
8524
8525
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8526
0
{
8527
0
    if (ImGuiWindow* window = FindWindowByName(name))
8528
0
        SetWindowCollapsed(window, collapsed, cond);
8529
0
}
8530
8531
void ImGui::SetWindowFocus()
8532
3.06k
{
8533
3.06k
    FocusWindow(GImGui->CurrentWindow);
8534
3.06k
}
8535
8536
void ImGui::SetWindowFocus(const char* name)
8537
0
{
8538
0
    if (name)
8539
0
    {
8540
0
        if (ImGuiWindow* window = FindWindowByName(name))
8541
0
            FocusWindow(window);
8542
0
    }
8543
0
    else
8544
0
    {
8545
0
        FocusWindow(NULL);
8546
0
    }
8547
0
}
8548
8549
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8550
0
{
8551
0
    ImGuiContext& g = *GImGui;
8552
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8553
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8554
0
    g.NextWindowData.PosVal = pos;
8555
0
    g.NextWindowData.PosPivotVal = pivot;
8556
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8557
0
    g.NextWindowData.PosUndock = true;
8558
0
}
8559
8560
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8561
90.5k
{
8562
90.5k
    ImGuiContext& g = *GImGui;
8563
90.5k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8564
90.5k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8565
90.5k
    g.NextWindowData.SizeVal = size;
8566
90.5k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8567
90.5k
}
8568
8569
// For each axis:
8570
// - Use 0.0f as min or FLT_MAX as max if you don't want limits, e.g. size_min = (500.0f, 0.0f), size_max = (FLT_MAX, FLT_MAX) sets a minimum width.
8571
// - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
8572
// - See "Demo->Examples->Constrained-resizing window" for examples.
8573
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8574
0
{
8575
0
    ImGuiContext& g = *GImGui;
8576
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8577
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8578
0
    g.NextWindowData.SizeCallback = custom_callback;
8579
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8580
0
}
8581
8582
// Content size = inner scrollable rectangle, padded with WindowPadding.
8583
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8584
void ImGui::SetNextWindowContentSize(const ImVec2& size)
8585
0
{
8586
0
    ImGuiContext& g = *GImGui;
8587
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8588
0
    g.NextWindowData.ContentSizeVal = ImTrunc(size);
8589
0
}
8590
8591
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8592
0
{
8593
0
    ImGuiContext& g = *GImGui;
8594
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8595
0
    g.NextWindowData.ScrollVal = scroll;
8596
0
}
8597
8598
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8599
0
{
8600
0
    ImGuiContext& g = *GImGui;
8601
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8602
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8603
0
    g.NextWindowData.CollapsedVal = collapsed;
8604
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8605
0
}
8606
8607
void ImGui::SetNextWindowFocus()
8608
0
{
8609
0
    ImGuiContext& g = *GImGui;
8610
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8611
0
}
8612
8613
void ImGui::SetNextWindowBgAlpha(float alpha)
8614
0
{
8615
0
    ImGuiContext& g = *GImGui;
8616
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8617
0
    g.NextWindowData.BgAlphaVal = alpha;
8618
0
}
8619
8620
void ImGui::SetNextWindowViewport(ImGuiID id)
8621
0
{
8622
0
    ImGuiContext& g = *GImGui;
8623
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8624
0
    g.NextWindowData.ViewportId = id;
8625
0
}
8626
8627
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8628
0
{
8629
0
    ImGuiContext& g = *GImGui;
8630
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8631
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8632
0
    g.NextWindowData.DockId = id;
8633
0
}
8634
8635
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8636
0
{
8637
0
    ImGuiContext& g = *GImGui;
8638
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8639
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8640
0
    g.NextWindowData.WindowClass = *window_class;
8641
0
}
8642
8643
// This is experimental and meant to be a toy for exploring a future/wider range of features.
8644
void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags)
8645
0
{
8646
0
    ImGuiContext& g = *GImGui;
8647
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasRefreshPolicy;
8648
0
    g.NextWindowData.RefreshFlagsVal = flags;
8649
0
}
8650
8651
ImDrawList* ImGui::GetWindowDrawList()
8652
11.4k
{
8653
11.4k
    ImGuiWindow* window = GetCurrentWindow();
8654
11.4k
    return window->DrawList;
8655
11.4k
}
8656
8657
float ImGui::GetWindowDpiScale()
8658
0
{
8659
0
    ImGuiContext& g = *GImGui;
8660
0
    return g.CurrentDpiScale;
8661
0
}
8662
8663
ImGuiViewport* ImGui::GetWindowViewport()
8664
0
{
8665
0
    ImGuiContext& g = *GImGui;
8666
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8667
0
    return g.CurrentViewport;
8668
0
}
8669
8670
ImFont* ImGui::GetFont()
8671
1.21M
{
8672
1.21M
    return GImGui->Font;
8673
1.21M
}
8674
8675
float ImGui::GetFontSize()
8676
1.21M
{
8677
1.21M
    return GImGui->FontSize;
8678
1.21M
}
8679
8680
ImVec2 ImGui::GetFontTexUvWhitePixel()
8681
0
{
8682
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8683
0
}
8684
8685
void ImGui::SetWindowFontScale(float scale)
8686
0
{
8687
0
    IM_ASSERT(scale > 0.0f);
8688
0
    ImGuiContext& g = *GImGui;
8689
0
    ImGuiWindow* window = GetCurrentWindow();
8690
0
    window->FontWindowScale = scale;
8691
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8692
0
    g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize;
8693
0
}
8694
8695
void ImGui::PushFocusScope(ImGuiID id)
8696
169k
{
8697
169k
    ImGuiContext& g = *GImGui;
8698
169k
    ImGuiFocusScopeData data;
8699
169k
    data.ID = id;
8700
169k
    data.WindowID = g.CurrentWindow->ID;
8701
169k
    g.FocusScopeStack.push_back(data);
8702
169k
    g.CurrentFocusScopeId = id;
8703
169k
}
8704
8705
void ImGui::PopFocusScope()
8706
169k
{
8707
169k
    ImGuiContext& g = *GImGui;
8708
169k
    if (g.FocusScopeStack.Size == 0)
8709
0
    {
8710
0
        IM_ASSERT_USER_ERROR(g.FocusScopeStack.Size > 0, "Calling PopFocusScope() too many times!");
8711
0
        return;
8712
0
    }
8713
169k
    g.FocusScopeStack.pop_back();
8714
169k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
8715
169k
}
8716
8717
void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
8718
5.05k
{
8719
5.05k
    ImGuiContext& g = *GImGui;
8720
5.05k
    g.NavFocusScopeId = focus_scope_id;
8721
5.05k
    g.NavFocusRoute.resize(0); // Invalidate
8722
5.05k
    if (focus_scope_id == 0)
8723
2.31k
        return;
8724
2.73k
    IM_ASSERT(g.NavWindow != NULL);
8725
8726
    // Store current path (in reverse order)
8727
2.73k
    if (focus_scope_id == g.CurrentFocusScopeId)
8728
2.46k
    {
8729
        // Top of focus stack contains local focus scopes inside current window
8730
4.92k
        for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
8731
2.46k
            g.NavFocusRoute.push_back(g.FocusScopeStack.Data[n]);
8732
2.46k
    }
8733
271
    else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
8734
269
        g.NavFocusRoute.push_back({ focus_scope_id, g.NavWindow->ID });
8735
2
    else
8736
2
        return;
8737
8738
    // Then follow on manually set ParentWindowForFocusRoute field (#6798)
8739
5.00k
    for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
8740
2.27k
        g.NavFocusRoute.push_back({ window->NavRootFocusScopeId, window->ID });
8741
2.72k
    IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
8742
2.72k
}
8743
8744
// Focus = move navigation cursor, set scrolling, set focus window.
8745
void ImGui::FocusItem()
8746
0
{
8747
0
    ImGuiContext& g = *GImGui;
8748
0
    ImGuiWindow* window = g.CurrentWindow;
8749
0
    IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8750
0
    if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8751
0
    {
8752
0
        IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8753
0
        return;
8754
0
    }
8755
8756
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight | ImGuiNavMoveFlags_NoSelect;
8757
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8758
0
    SetNavWindow(window);
8759
0
    NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8760
0
    NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8761
0
}
8762
8763
void ImGui::ActivateItemByID(ImGuiID id)
8764
0
{
8765
0
    ImGuiContext& g = *GImGui;
8766
0
    g.NavNextActivateId = id;
8767
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8768
0
}
8769
8770
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8771
// But ActivateItem() should function without altering scroll/focus?
8772
void ImGui::SetKeyboardFocusHere(int offset)
8773
0
{
8774
0
    ImGuiContext& g = *GImGui;
8775
0
    ImGuiWindow* window = g.CurrentWindow;
8776
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8777
0
    IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8778
8779
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8780
    // When we refactor this function into ActivateItem() we may want to make this an option.
8781
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8782
    // is also automatically dropped in the event g.ActiveId is stolen.
8783
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8784
0
    {
8785
0
        IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8786
0
        return;
8787
0
    }
8788
8789
0
    SetNavWindow(window);
8790
8791
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight;
8792
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8793
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8794
0
    if (offset == -1)
8795
0
    {
8796
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8797
0
    }
8798
0
    else
8799
0
    {
8800
0
        g.NavTabbingDir = 1;
8801
0
        g.NavTabbingCounter = offset + 1;
8802
0
    }
8803
0
}
8804
8805
void ImGui::SetItemDefaultFocus()
8806
0
{
8807
0
    ImGuiContext& g = *GImGui;
8808
0
    ImGuiWindow* window = g.CurrentWindow;
8809
0
    if (!window->Appearing)
8810
0
        return;
8811
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8812
0
        return;
8813
8814
0
    g.NavInitRequest = false;
8815
0
    NavApplyItemToResult(&g.NavInitResult);
8816
0
    NavUpdateAnyRequestFlag();
8817
8818
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8819
0
    if (!window->ClipRect.Contains(g.LastItemData.Rect))
8820
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8821
0
}
8822
8823
void ImGui::SetStateStorage(ImGuiStorage* tree)
8824
0
{
8825
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8826
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8827
0
}
8828
8829
ImGuiStorage* ImGui::GetStateStorage()
8830
0
{
8831
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8832
0
    return window->DC.StateStorage;
8833
0
}
8834
8835
bool ImGui::IsRectVisible(const ImVec2& size)
8836
0
{
8837
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8838
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8839
0
}
8840
8841
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8842
0
{
8843
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8844
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8845
0
}
8846
8847
//-----------------------------------------------------------------------------
8848
// [SECTION] ID STACK
8849
//-----------------------------------------------------------------------------
8850
8851
// This is one of the very rare legacy case where we use ImGuiWindow methods,
8852
// it should ideally be flattened at some point but it's been used a lots by widgets.
8853
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
8854
201k
{
8855
201k
    ImGuiID seed = IDStack.back();
8856
201k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8857
201k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8858
201k
    ImGuiContext& g = *Ctx;
8859
201k
    if (g.DebugHookIdInfo == id)
8860
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8861
201k
#endif
8862
201k
    return id;
8863
201k
}
8864
8865
ImGuiID ImGuiWindow::GetID(const void* ptr)
8866
0
{
8867
0
    ImGuiID seed = IDStack.back();
8868
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
8869
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8870
0
    ImGuiContext& g = *Ctx;
8871
0
    if (g.DebugHookIdInfo == id)
8872
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
8873
0
#endif
8874
0
    return id;
8875
0
}
8876
8877
ImGuiID ImGuiWindow::GetID(int n)
8878
68.9k
{
8879
68.9k
    ImGuiID seed = IDStack.back();
8880
68.9k
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8881
68.9k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8882
68.9k
    ImGuiContext& g = *Ctx;
8883
68.9k
    if (g.DebugHookIdInfo == id)
8884
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8885
68.9k
#endif
8886
68.9k
    return id;
8887
68.9k
}
8888
8889
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
8890
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
8891
0
{
8892
0
    ImGuiID seed = IDStack.back();
8893
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
8894
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
8895
0
    return id;
8896
0
}
8897
8898
void ImGui::PushID(const char* str_id)
8899
11.4k
{
8900
11.4k
    ImGuiContext& g = *GImGui;
8901
11.4k
    ImGuiWindow* window = g.CurrentWindow;
8902
11.4k
    ImGuiID id = window->GetID(str_id);
8903
11.4k
    window->IDStack.push_back(id);
8904
11.4k
}
8905
8906
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8907
0
{
8908
0
    ImGuiContext& g = *GImGui;
8909
0
    ImGuiWindow* window = g.CurrentWindow;
8910
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8911
0
    window->IDStack.push_back(id);
8912
0
}
8913
8914
void ImGui::PushID(const void* ptr_id)
8915
0
{
8916
0
    ImGuiContext& g = *GImGui;
8917
0
    ImGuiWindow* window = g.CurrentWindow;
8918
0
    ImGuiID id = window->GetID(ptr_id);
8919
0
    window->IDStack.push_back(id);
8920
0
}
8921
8922
void ImGui::PushID(int int_id)
8923
0
{
8924
0
    ImGuiContext& g = *GImGui;
8925
0
    ImGuiWindow* window = g.CurrentWindow;
8926
0
    ImGuiID id = window->GetID(int_id);
8927
0
    window->IDStack.push_back(id);
8928
0
}
8929
8930
// Push a given id value ignoring the ID stack as a seed.
8931
void ImGui::PushOverrideID(ImGuiID id)
8932
0
{
8933
0
    ImGuiContext& g = *GImGui;
8934
0
    ImGuiWindow* window = g.CurrentWindow;
8935
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8936
0
    if (g.DebugHookIdInfo == id)
8937
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8938
0
#endif
8939
0
    window->IDStack.push_back(id);
8940
0
}
8941
8942
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8943
// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
8944
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8945
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8946
0
{
8947
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8948
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8949
0
    ImGuiContext& g = *GImGui;
8950
0
    if (g.DebugHookIdInfo == id)
8951
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8952
0
#endif
8953
0
    return id;
8954
0
}
8955
8956
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8957
0
{
8958
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8959
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8960
0
    ImGuiContext& g = *GImGui;
8961
0
    if (g.DebugHookIdInfo == id)
8962
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8963
0
#endif
8964
0
    return id;
8965
0
}
8966
8967
void ImGui::PopID()
8968
11.4k
{
8969
11.4k
    ImGuiWindow* window = GImGui->CurrentWindow;
8970
11.4k
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8971
11.4k
    window->IDStack.pop_back();
8972
11.4k
}
8973
8974
ImGuiID ImGui::GetID(const char* str_id)
8975
0
{
8976
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8977
0
    return window->GetID(str_id);
8978
0
}
8979
8980
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8981
0
{
8982
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8983
0
    return window->GetID(str_id_begin, str_id_end);
8984
0
}
8985
8986
ImGuiID ImGui::GetID(const void* ptr_id)
8987
0
{
8988
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8989
0
    return window->GetID(ptr_id);
8990
0
}
8991
8992
//-----------------------------------------------------------------------------
8993
// [SECTION] INPUTS
8994
//-----------------------------------------------------------------------------
8995
// - GetModForModKey() [Internal]
8996
// - FixupKeyChord() [Internal]
8997
// - GetKeyData() [Internal]
8998
// - GetKeyIndex() [Internal]
8999
// - GetKeyName()
9000
// - GetKeyChordName() [Internal]
9001
// - CalcTypematicRepeatAmount() [Internal]
9002
// - GetTypematicRepeatRate() [Internal]
9003
// - GetKeyPressedAmount() [Internal]
9004
// - GetKeyMagnitude2d() [Internal]
9005
//-----------------------------------------------------------------------------
9006
// - UpdateKeyRoutingTable() [Internal]
9007
// - GetRoutingIdFromOwnerId() [Internal]
9008
// - GetShortcutRoutingData() [Internal]
9009
// - CalcRoutingScore() [Internal]
9010
// - SetShortcutRouting() [Internal]
9011
// - TestShortcutRouting() [Internal]
9012
//-----------------------------------------------------------------------------
9013
// - IsKeyDown()
9014
// - IsKeyPressed()
9015
// - IsKeyReleased()
9016
//-----------------------------------------------------------------------------
9017
// - IsMouseDown()
9018
// - IsMouseClicked()
9019
// - IsMouseReleased()
9020
// - IsMouseDoubleClicked()
9021
// - GetMouseClickedCount()
9022
// - IsMouseHoveringRect() [Internal]
9023
// - IsMouseDragPastThreshold() [Internal]
9024
// - IsMouseDragging()
9025
// - GetMousePos()
9026
// - SetMousePos() [Internal]
9027
// - GetMousePosOnOpeningCurrentPopup()
9028
// - IsMousePosValid()
9029
// - IsAnyMouseDown()
9030
// - GetMouseDragDelta()
9031
// - ResetMouseDragDelta()
9032
// - GetMouseCursor()
9033
// - SetMouseCursor()
9034
//-----------------------------------------------------------------------------
9035
// - UpdateAliasKey()
9036
// - GetMergedModsFromKeys()
9037
// - UpdateKeyboardInputs()
9038
// - UpdateMouseInputs()
9039
//-----------------------------------------------------------------------------
9040
// - LockWheelingWindow [Internal]
9041
// - FindBestWheelingWindow [Internal]
9042
// - UpdateMouseWheel() [Internal]
9043
//-----------------------------------------------------------------------------
9044
// - SetNextFrameWantCaptureKeyboard()
9045
// - SetNextFrameWantCaptureMouse()
9046
//-----------------------------------------------------------------------------
9047
// - GetInputSourceName() [Internal]
9048
// - DebugPrintInputEvent() [Internal]
9049
// - UpdateInputEvents() [Internal]
9050
//-----------------------------------------------------------------------------
9051
// - GetKeyOwner() [Internal]
9052
// - TestKeyOwner() [Internal]
9053
// - SetKeyOwner() [Internal]
9054
// - SetItemKeyOwner() [Internal]
9055
// - Shortcut() [Internal]
9056
//-----------------------------------------------------------------------------
9057
9058
static ImGuiKeyChord GetModForModKey(ImGuiKey key)
9059
0
{
9060
0
    if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
9061
0
        return ImGuiMod_Ctrl;
9062
0
    if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
9063
0
        return ImGuiMod_Shift;
9064
0
    if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
9065
0
        return ImGuiMod_Alt;
9066
0
    if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
9067
0
        return ImGuiMod_Super;
9068
0
    return ImGuiMod_None;
9069
0
}
9070
9071
ImGuiKeyChord ImGui::FixupKeyChord(ImGuiKeyChord key_chord)
9072
316k
{
9073
    // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9074
316k
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9075
316k
    if (IsModKey(key))
9076
0
        key_chord |= GetModForModKey(key);
9077
316k
    return key_chord;
9078
316k
}
9079
9080
ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
9081
2.08M
{
9082
2.08M
    ImGuiContext& g = *ctx;
9083
9084
    // Special storage location for mods
9085
2.08M
    if (key & ImGuiMod_Mask_)
9086
632k
        key = ConvertSingleModFlagToKey(key);
9087
9088
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9089
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
9090
    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
9091
        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
9092
#else
9093
2.08M
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
9094
2.08M
#endif
9095
2.08M
    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
9096
2.08M
}
9097
9098
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9099
// Formally moved to obsolete section in 1.90.5 in spite of documented as obsolete since 1.87
9100
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
9101
{
9102
    ImGuiContext& g = *GImGui;
9103
    IM_ASSERT(IsNamedKey(key));
9104
    const ImGuiKeyData* key_data = GetKeyData(key);
9105
    return (ImGuiKey)(key_data - g.IO.KeysData);
9106
}
9107
#endif
9108
9109
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
9110
static const char* const GKeyNames[] =
9111
{
9112
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
9113
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
9114
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
9115
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
9116
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
9117
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
9118
    "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
9119
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
9120
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
9121
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
9122
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
9123
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
9124
    "AppBack", "AppForward",
9125
    "GamepadStart", "GamepadBack",
9126
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
9127
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
9128
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
9129
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
9130
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
9131
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
9132
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
9133
};
9134
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
9135
9136
const char* ImGui::GetKeyName(ImGuiKey key)
9137
0
{
9138
0
    if (key == ImGuiKey_None)
9139
0
        return "None";
9140
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
9141
0
    IM_ASSERT(IsNamedKeyOrMod(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
9142
#else
9143
    ImGuiContext& g = *GImGui;
9144
    if (IsLegacyKey(key))
9145
    {
9146
        if (g.IO.KeyMap[key] == -1)
9147
            return "N/A";
9148
        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
9149
        key = (ImGuiKey)g.IO.KeyMap[key];
9150
    }
9151
#endif
9152
0
    if (key & ImGuiMod_Mask_)
9153
0
        key = ConvertSingleModFlagToKey(key);
9154
0
    if (!IsNamedKey(key))
9155
0
        return "Unknown";
9156
9157
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
9158
0
}
9159
9160
// Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super.
9161
// Lifetime of return value: valid until next call to same function.
9162
const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
9163
0
{
9164
0
    ImGuiContext& g = *GImGui;
9165
9166
0
    const ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9167
0
    if (IsModKey(key))
9168
0
        key_chord &= ~GetModForModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift"
9169
0
    ImFormatString(g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), "%s%s%s%s%s",
9170
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
9171
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
9172
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
9173
0
        (key_chord & ImGuiMod_Super) ? "Super+" : "",
9174
0
        (key != ImGuiKey_None || key_chord == ImGuiKey_None) ? GetKeyName(key) : "");
9175
0
    size_t len;
9176
0
    if (key == ImGuiKey_None && key_chord != 0)
9177
0
        if ((len = strlen(g.TempKeychordName)) != 0) // Remove trailing '+'
9178
0
            g.TempKeychordName[len - 1] = 0;
9179
0
    return g.TempKeychordName;
9180
0
}
9181
9182
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
9183
// t1 = current time (e.g.: g.Time)
9184
// An event is triggered at:
9185
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
9186
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
9187
33
{
9188
33
    if (t1 == 0.0f)
9189
0
        return 1;
9190
33
    if (t0 >= t1)
9191
0
        return 0;
9192
33
    if (repeat_rate <= 0.0f)
9193
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
9194
33
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
9195
33
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
9196
33
    const int count = count_t1 - count_t0;
9197
33
    return count;
9198
33
}
9199
9200
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
9201
1.93k
{
9202
1.93k
    ImGuiContext& g = *GImGui;
9203
1.93k
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
9204
1.93k
    {
9205
455
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
9206
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
9207
1.48k
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
9208
1.93k
    }
9209
1.93k
}
9210
9211
// Return value representing the number of presses in the last time period, for the given repeat rate
9212
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
9213
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
9214
33
{
9215
33
    ImGuiContext& g = *GImGui;
9216
33
    const ImGuiKeyData* key_data = GetKeyData(key);
9217
33
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9218
0
        return 0;
9219
33
    const float t = key_data->DownDuration;
9220
33
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
9221
33
}
9222
9223
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
9224
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
9225
0
{
9226
0
    return ImVec2(
9227
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
9228
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
9229
0
}
9230
9231
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
9232
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
9233
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
9234
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
9235
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
9236
79.1k
{
9237
79.1k
    ImGuiContext& g = *GImGui;
9238
79.1k
    rt->EntriesNext.resize(0);
9239
12.2M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9240
12.1M
    {
9241
12.1M
        const int new_routing_start_idx = rt->EntriesNext.Size;
9242
12.1M
        ImGuiKeyRoutingData* routing_entry;
9243
12.1M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
9244
0
        {
9245
0
            routing_entry = &rt->Entries[old_routing_idx];
9246
0
            routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
9247
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
9248
0
            routing_entry->RoutingNext = ImGuiKeyOwner_NoOwner;
9249
0
            routing_entry->RoutingNextScore = 255;
9250
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_NoOwner)
9251
0
                continue;
9252
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
9253
9254
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
9255
            // This is the result of previous frame's SetShortcutRouting() call.
9256
0
            if (routing_entry->Mods == g.IO.KeyMods)
9257
0
            {
9258
0
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9259
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
9260
0
                {
9261
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
9262
                    //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
9263
0
                }
9264
0
            }
9265
0
        }
9266
9267
        // Rewrite linked-list
9268
12.1M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
9269
12.1M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
9270
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
9271
12.1M
    }
9272
79.1k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
9273
79.1k
}
9274
9275
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
9276
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
9277
0
{
9278
0
    ImGuiContext& g = *GImGui;
9279
0
    return (owner_id != ImGuiKeyOwner_NoOwner && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
9280
0
}
9281
9282
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
9283
0
{
9284
    // Majority of shortcuts will be Key + any number of Mods
9285
    // We accept _Single_ mod with ImGuiKey_None.
9286
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
9287
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
9288
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
9289
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
9290
0
    ImGuiContext& g = *GImGui;
9291
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
9292
0
    ImGuiKeyRoutingData* routing_data;
9293
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9294
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9295
0
    if (key == ImGuiKey_None)
9296
0
        key = ConvertSingleModFlagToKey(mods);
9297
0
    IM_ASSERT(IsNamedKey(key));
9298
9299
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
9300
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
9301
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
9302
0
    {
9303
0
        routing_data = &rt->Entries[idx];
9304
0
        if (routing_data->Mods == mods)
9305
0
            return routing_data;
9306
0
    }
9307
9308
    // Add to linked-list
9309
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
9310
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
9311
0
    routing_data = &rt->Entries[routing_data_idx];
9312
0
    routing_data->Mods = (ImU16)mods;
9313
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
9314
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
9315
0
    return routing_data;
9316
0
}
9317
9318
// Current score encoding (lower is highest priority):
9319
//  -   0: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive
9320
//  -   1: ImGuiInputFlags_ActiveItem or ImGuiInputFlags_RouteFocused (if item active)
9321
//  -   2: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused
9322
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
9323
//  - 254: ImGuiInputFlags_RouteGlobal
9324
//  - 255: never route
9325
// 'flags' should include an explicit routing policy
9326
static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
9327
0
{
9328
0
    ImGuiContext& g = *GImGui;
9329
0
    if (flags & ImGuiInputFlags_RouteFocused)
9330
0
    {
9331
        // ActiveID gets top priority
9332
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
9333
0
        if (owner_id != 0 && g.ActiveId == owner_id)
9334
0
            return 1;
9335
9336
        // Score based on distance to focused window (lower is better)
9337
        // Assuming both windows are submitting a routing request,
9338
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
9339
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
9340
        // Assuming only WindowA is submitting a routing request,
9341
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
9342
        // This essentially follow the window->ParentWindowForFocusRoute chain.
9343
0
        if (focus_scope_id == 0)
9344
0
            return 255;
9345
0
        for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
9346
0
            if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
9347
0
                return 3 + index_in_focus_path;
9348
0
        return 255;
9349
0
    }
9350
0
    else if (flags & ImGuiInputFlags_RouteActive)
9351
0
    {
9352
0
        if (owner_id != 0 && g.ActiveId == owner_id)
9353
0
            return 1;
9354
0
        return 255;
9355
0
    }
9356
0
    else if (flags & ImGuiInputFlags_RouteGlobal)
9357
0
    {
9358
0
        if (flags & ImGuiInputFlags_RouteOverActive)
9359
0
            return 0;
9360
0
        if (flags & ImGuiInputFlags_RouteOverFocused)
9361
0
            return 2;
9362
0
        return 254;
9363
0
    }
9364
0
    IM_ASSERT(0);
9365
0
    return 0;
9366
0
}
9367
9368
// We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
9369
// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
9370
static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
9371
0
{
9372
    // Mimic 'ignore_char_inputs' logic in InputText()
9373
0
    ImGuiContext& g = *GImGui;
9374
9375
    // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
9376
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9377
0
    const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Ctrl));
9378
0
    if (ignore_char_inputs)
9379
0
        return false;
9380
9381
    // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
9382
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9383
0
    return g.KeysMayBeCharInput.TestBit(key);
9384
0
}
9385
9386
// Request a desired route for an input chord (key + mods).
9387
// Return true if the route is available this frame.
9388
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
9389
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
9390
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
9391
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
9392
158k
{
9393
158k
    ImGuiContext& g = *GImGui;
9394
158k
    if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
9395
0
        flags |= ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
9396
158k
    else
9397
158k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteTypeMask_)); // Check that only 1 routing flag is used
9398
158k
    IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_NoOwner);
9399
158k
    if (flags & (ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused))
9400
158k
        IM_ASSERT(flags & ImGuiInputFlags_RouteGlobal);
9401
9402
    // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9403
158k
    key_chord = FixupKeyChord(key_chord);
9404
9405
    // [DEBUG] Debug break requested by user
9406
158k
    if (g.DebugBreakInShortcutRouting == key_chord)
9407
0
        IM_DEBUG_BREAK();
9408
9409
158k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
9410
0
        if (g.NavWindow == NULL)
9411
0
            return false;
9412
9413
    // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
9414
158k
    if (flags & ImGuiInputFlags_RouteAlways)
9415
158k
    {
9416
158k
        IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register\n", GetKeyChordName(key_chord), flags, owner_id);
9417
158k
        return true;
9418
158k
    }
9419
9420
    // Specific culling when there's an active item.
9421
0
    if (g.ActiveId != 0 && g.ActiveId != owner_id)
9422
0
    {
9423
0
        if (flags & ImGuiInputFlags_RouteActive)
9424
0
            return false;
9425
9426
        // Cull shortcuts with no modifiers when it could generate a character.
9427
        // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
9428
        // but  Shortcut(Ctrl+G) should generally trigger when InputText() is active.
9429
        // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
9430
        // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
9431
0
        if (g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
9432
0
        {
9433
0
            IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input\n", GetKeyChordName(key_chord), flags, owner_id);
9434
0
            return false;
9435
0
        }
9436
9437
        // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
9438
0
        if ((flags & ImGuiInputFlags_RouteOverActive) == 0 && g.ActiveIdUsingAllKeyboardKeys)
9439
0
        {
9440
0
            ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9441
0
            if (key == ImGuiKey_None)
9442
0
                key = ConvertSingleModFlagToKey((ImGuiKey)(key_chord & ImGuiMod_Mask_));
9443
0
            if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9444
0
                return false;
9445
0
        }
9446
0
    }
9447
9448
    // Where do we evaluate route for?
9449
0
    ImGuiID focus_scope_id = g.CurrentFocusScopeId;
9450
0
    if (flags & ImGuiInputFlags_RouteFromRootWindow)
9451
0
        focus_scope_id = g.CurrentWindow->RootWindow->ID; // See PushFocusScope() call in Begin()
9452
9453
0
    const int score = CalcRoutingScore(focus_scope_id, owner_id, flags);
9454
0
    IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> score %d\n", GetKeyChordName(key_chord), flags, owner_id, score);
9455
0
    if (score == 255)
9456
0
        return false;
9457
9458
    // Submit routing for NEXT frame (assuming score is sufficient)
9459
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
9460
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
9461
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
9462
0
    if (score < routing_data->RoutingNextScore)
9463
0
    {
9464
0
        routing_data->RoutingNext = owner_id;
9465
0
        routing_data->RoutingNextScore = (ImU8)score;
9466
0
    }
9467
9468
    // Return routing state for CURRENT frame
9469
0
    if (routing_data->RoutingCurr == owner_id)
9470
0
        IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
9471
0
    return routing_data->RoutingCurr == owner_id;
9472
0
}
9473
9474
// Currently unused by core (but used by tests)
9475
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
9476
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
9477
0
{
9478
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
9479
0
    key_chord = FixupKeyChord(key_chord);
9480
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
9481
0
    return routing_data->RoutingCurr == routing_id;
9482
0
}
9483
9484
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
9485
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
9486
bool ImGui::IsKeyDown(ImGuiKey key)
9487
1.19M
{
9488
1.19M
    return IsKeyDown(key, ImGuiKeyOwner_Any);
9489
1.19M
}
9490
9491
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
9492
1.19M
{
9493
1.19M
    const ImGuiKeyData* key_data = GetKeyData(key);
9494
1.19M
    if (!key_data->Down)
9495
1.15M
        return false;
9496
46.2k
    if (!TestKeyOwner(key, owner_id))
9497
2
        return false;
9498
46.2k
    return true;
9499
46.2k
}
9500
9501
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
9502
48.8k
{
9503
48.8k
    return IsKeyPressed(key, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
9504
48.8k
}
9505
9506
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
9507
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id)
9508
313k
{
9509
313k
    const ImGuiKeyData* key_data = GetKeyData(key);
9510
313k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9511
303k
        return false;
9512
9.61k
    const float t = key_data->DownDuration;
9513
9.61k
    if (t < 0.0f)
9514
0
        return false;
9515
9.61k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9516
9.61k
    if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
9517
509
        flags |= ImGuiInputFlags_Repeat;
9518
9519
9.61k
    bool pressed = (t == 0.0f);
9520
9.61k
    if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
9521
1.93k
    {
9522
1.93k
        float repeat_delay, repeat_rate;
9523
1.93k
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
9524
1.93k
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
9525
1.93k
        if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
9526
0
        {
9527
            // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
9528
            // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
9529
0
            ImGuiContext& g = *GImGui;
9530
0
            double key_pressed_time = g.Time - t + 0.00001f;
9531
0
            if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
9532
0
                pressed = false;
9533
0
            if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
9534
0
                pressed = false;
9535
0
            if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
9536
0
                pressed = false;
9537
0
        }
9538
1.93k
    }
9539
9.61k
    if (!pressed)
9540
7.23k
        return false;
9541
2.37k
    if (!TestKeyOwner(key, owner_id))
9542
0
        return false;
9543
2.37k
    return true;
9544
2.37k
}
9545
9546
bool ImGui::IsKeyReleased(ImGuiKey key)
9547
4.55k
{
9548
4.55k
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
9549
4.55k
}
9550
9551
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
9552
4.55k
{
9553
4.55k
    const ImGuiKeyData* key_data = GetKeyData(key);
9554
4.55k
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
9555
3.83k
        return false;
9556
723
    if (!TestKeyOwner(key, owner_id))
9557
0
        return false;
9558
723
    return true;
9559
723
}
9560
9561
bool ImGui::IsMouseDown(ImGuiMouseButton button)
9562
3
{
9563
3
    ImGuiContext& g = *GImGui;
9564
3
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9565
3
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
9566
3
}
9567
9568
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
9569
1
{
9570
1
    ImGuiContext& g = *GImGui;
9571
1
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9572
1
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
9573
1
}
9574
9575
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
9576
4
{
9577
4
    return IsMouseClicked(button, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
9578
4
}
9579
9580
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id)
9581
37
{
9582
37
    ImGuiContext& g = *GImGui;
9583
37
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9584
37
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9585
23
        return false;
9586
14
    const float t = g.IO.MouseDownDuration[button];
9587
14
    if (t < 0.0f)
9588
0
        return false;
9589
14
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
9590
9591
14
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
9592
14
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
9593
14
    if (!pressed)
9594
13
        return false;
9595
9596
1
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
9597
0
        return false;
9598
9599
1
    return true;
9600
1
}
9601
9602
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
9603
0
{
9604
0
    ImGuiContext& g = *GImGui;
9605
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9606
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
9607
0
}
9608
9609
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
9610
33
{
9611
33
    ImGuiContext& g = *GImGui;
9612
33
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9613
33
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
9614
33
}
9615
9616
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
9617
3
{
9618
3
    ImGuiContext& g = *GImGui;
9619
3
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9620
3
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
9621
3
}
9622
9623
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
9624
0
{
9625
0
    ImGuiContext& g = *GImGui;
9626
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9627
0
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id);
9628
0
}
9629
9630
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
9631
0
{
9632
0
    ImGuiContext& g = *GImGui;
9633
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9634
0
    return g.IO.MouseClickedCount[button];
9635
0
}
9636
9637
// Test if mouse cursor is hovering given rectangle
9638
// NB- Rectangle is clipped by our current clip setting
9639
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
9640
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
9641
409k
{
9642
409k
    ImGuiContext& g = *GImGui;
9643
9644
    // Clip
9645
409k
    ImRect rect_clipped(r_min, r_max);
9646
409k
    if (clip)
9647
239k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
9648
9649
    // Hit testing, expanded for touch input
9650
409k
    if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
9651
402k
        return false;
9652
7.36k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
9653
0
        return false;
9654
7.36k
    return true;
9655
7.36k
}
9656
9657
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
9658
// [Internal] This doesn't test if the button is pressed
9659
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
9660
54
{
9661
54
    ImGuiContext& g = *GImGui;
9662
54
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9663
54
    if (lock_threshold < 0.0f)
9664
54
        lock_threshold = g.IO.MouseDragThreshold;
9665
54
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
9666
54
}
9667
9668
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
9669
54
{
9670
54
    ImGuiContext& g = *GImGui;
9671
54
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9672
54
    if (!g.IO.MouseDown[button])
9673
0
        return false;
9674
54
    return IsMouseDragPastThreshold(button, lock_threshold);
9675
54
}
9676
9677
ImVec2 ImGui::GetMousePos()
9678
9.79k
{
9679
9.79k
    ImGuiContext& g = *GImGui;
9680
9.79k
    return g.IO.MousePos;
9681
9.79k
}
9682
9683
// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
9684
// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
9685
void ImGui::TeleportMousePos(const ImVec2& pos)
9686
0
{
9687
0
    ImGuiContext& g = *GImGui;
9688
0
    g.IO.MousePos = g.IO.MousePosPrev = pos;
9689
0
    g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
9690
0
    g.IO.WantSetMousePos = true;
9691
    //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9692
0
}
9693
9694
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
9695
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9696
0
{
9697
0
    ImGuiContext& g = *GImGui;
9698
0
    if (g.BeginPopupStack.Size > 0)
9699
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9700
0
    return g.IO.MousePos;
9701
0
}
9702
9703
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9704
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9705
308k
{
9706
    // The assert is only to silence a false-positive in XCode Static Analysis.
9707
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
9708
308k
    IM_ASSERT(GImGui != NULL);
9709
308k
    const float MOUSE_INVALID = -256000.0f;
9710
308k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9711
308k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9712
308k
}
9713
9714
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
9715
bool ImGui::IsAnyMouseDown()
9716
0
{
9717
0
    ImGuiContext& g = *GImGui;
9718
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9719
0
        if (g.IO.MouseDown[n])
9720
0
            return true;
9721
0
    return false;
9722
0
}
9723
9724
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9725
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9726
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9727
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9728
0
{
9729
0
    ImGuiContext& g = *GImGui;
9730
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9731
0
    if (lock_threshold < 0.0f)
9732
0
        lock_threshold = g.IO.MouseDragThreshold;
9733
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9734
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9735
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
9736
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
9737
0
    return ImVec2(0.0f, 0.0f);
9738
0
}
9739
9740
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9741
0
{
9742
0
    ImGuiContext& g = *GImGui;
9743
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9744
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9745
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
9746
0
}
9747
9748
// Get desired mouse cursor shape.
9749
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9750
// updated during the frame, and locked in EndFrame()/Render().
9751
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9752
ImGuiMouseCursor ImGui::GetMouseCursor()
9753
0
{
9754
0
    ImGuiContext& g = *GImGui;
9755
0
    return g.MouseCursor;
9756
0
}
9757
9758
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9759
0
{
9760
0
    ImGuiContext& g = *GImGui;
9761
0
    g.MouseCursor = cursor_type;
9762
0
}
9763
9764
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9765
553k
{
9766
553k
    IM_ASSERT(ImGui::IsAliasKey(key));
9767
553k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9768
553k
    key_data->Down = v;
9769
553k
    key_data->AnalogValue = analog_value;
9770
553k
}
9771
9772
// [Internal] Do not use directly
9773
static ImGuiKeyChord GetMergedModsFromKeys()
9774
158k
{
9775
158k
    ImGuiKeyChord mods = 0;
9776
158k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
9777
158k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
9778
158k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
9779
158k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
9780
158k
    return mods;
9781
158k
}
9782
9783
static void ImGui::UpdateKeyboardInputs()
9784
79.1k
{
9785
79.1k
    ImGuiContext& g = *GImGui;
9786
79.1k
    ImGuiIO& io = g.IO;
9787
9788
79.1k
    if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
9789
0
        io.ClearInputKeys();
9790
9791
    // Import legacy keys or verify they are not used
9792
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9793
    if (io.BackendUsingLegacyKeyArrays == 0)
9794
    {
9795
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9796
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9797
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
9798
    }
9799
    else
9800
    {
9801
        if (g.FrameCount == 0)
9802
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9803
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9804
9805
        // Build reverse KeyMap (Named -> Legacy)
9806
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9807
            if (io.KeyMap[n] != -1)
9808
            {
9809
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9810
                io.KeyMap[io.KeyMap[n]] = n;
9811
            }
9812
9813
        // Import legacy keys into new ones
9814
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9815
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9816
            {
9817
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9818
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9819
                io.KeysData[key].Down = io.KeysDown[n];
9820
                if (key != n)
9821
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9822
                io.BackendUsingLegacyKeyArrays = 1;
9823
            }
9824
        if (io.BackendUsingLegacyKeyArrays == 1)
9825
        {
9826
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9827
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
9828
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
9829
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
9830
        }
9831
    }
9832
#endif
9833
9834
    // Import legacy ImGuiNavInput_ io inputs and convert to gamepad keys
9835
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9836
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9837
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9838
    {
9839
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9840
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9841
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9842
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9843
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9844
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9845
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9846
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9847
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9848
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9849
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9850
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9851
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9852
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9853
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9854
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9855
        #undef NAV_MAP_KEY
9856
    }
9857
#endif
9858
9859
    // Update aliases
9860
474k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9861
395k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9862
79.1k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9863
79.1k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9864
9865
    // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
9866
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9867
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9868
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9869
79.1k
    const ImGuiKeyChord prev_key_mods = io.KeyMods;
9870
79.1k
    io.KeyMods = GetMergedModsFromKeys();
9871
79.1k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9872
79.1k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9873
79.1k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9874
79.1k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9875
79.1k
    if (prev_key_mods != io.KeyMods)
9876
0
        g.LastKeyModsChangeTime = g.Time;
9877
79.1k
    if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
9878
0
        g.LastKeyModsChangeFromNoneTime = g.Time;
9879
9880
    // Clear gamepad data if disabled
9881
79.1k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9882
1.97M
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9883
1.89M
        {
9884
1.89M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9885
1.89M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9886
1.89M
        }
9887
9888
    // Update keys
9889
12.2M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9890
12.1M
    {
9891
12.1M
        ImGuiKeyData* key_data = &io.KeysData[i];
9892
12.1M
        key_data->DownDurationPrev = key_data->DownDuration;
9893
12.1M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9894
12.1M
        if (key_data->DownDuration == 0.0f)
9895
12.1k
        {
9896
12.1k
            ImGuiKey key = (ImGuiKey)(ImGuiKey_KeysData_OFFSET + i);
9897
12.1k
            if (IsKeyboardKey(key))
9898
4.69k
                g.LastKeyboardKeyPressTime = g.Time;
9899
7.46k
            else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
9900
0
                g.LastKeyboardKeyPressTime = g.Time;
9901
12.1k
        }
9902
12.1M
    }
9903
9904
    // Update keys/input owner (named keys only): one entry per key
9905
12.2M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9906
12.1M
    {
9907
12.1M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9908
12.1M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9909
12.1M
        owner_data->OwnerCurr = owner_data->OwnerNext;
9910
12.1M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9911
12.0M
            owner_data->OwnerNext = ImGuiKeyOwner_NoOwner;
9912
12.1M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
9913
12.1M
    }
9914
9915
    // Update key routing (for e.g. shortcuts)
9916
79.1k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
9917
79.1k
}
9918
9919
static void ImGui::UpdateMouseInputs()
9920
79.1k
{
9921
79.1k
    ImGuiContext& g = *GImGui;
9922
79.1k
    ImGuiIO& io = g.IO;
9923
9924
    // Mouse Wheel swapping flag
9925
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9926
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9927
    // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9928
    // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9929
79.1k
    io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9930
9931
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9932
79.1k
    if (IsMousePosValid(&io.MousePos))
9933
48.4k
        io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
9934
9935
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9936
79.1k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9937
48.2k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
9938
30.9k
    else
9939
30.9k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
9940
9941
    // Update stationary timer.
9942
    // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9943
79.1k
    const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9944
79.1k
    const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9945
79.1k
    g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9946
    //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9947
9948
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9949
79.1k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9950
2.98k
        g.NavDisableMouseHover = false;
9951
9952
474k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9953
395k
    {
9954
395k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9955
395k
        io.MouseClickedCount[i] = 0; // Will be filled below
9956
395k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9957
395k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9958
395k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9959
395k
        if (io.MouseClicked[i])
9960
4.10k
        {
9961
4.10k
            bool is_repeated_click = false;
9962
4.10k
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9963
3.44k
            {
9964
3.44k
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9965
3.44k
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9966
3.27k
                    is_repeated_click = true;
9967
3.44k
            }
9968
4.10k
            if (is_repeated_click)
9969
3.27k
                io.MouseClickedLastCount[i]++;
9970
830
            else
9971
830
                io.MouseClickedLastCount[i] = 1;
9972
4.10k
            io.MouseClickedTime[i] = g.Time;
9973
4.10k
            io.MouseClickedPos[i] = io.MousePos;
9974
4.10k
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9975
4.10k
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
9976
4.10k
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
9977
4.10k
        }
9978
391k
        else if (io.MouseDown[i])
9979
85.4k
        {
9980
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9981
85.4k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9982
85.4k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
9983
85.4k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
9984
85.4k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
9985
85.4k
        }
9986
9987
        // We provide io.MouseDoubleClicked[] as a legacy service
9988
395k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9989
9990
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9991
395k
        if (io.MouseClicked[i])
9992
4.10k
            g.NavDisableMouseHover = false;
9993
395k
    }
9994
79.1k
}
9995
9996
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9997
0
{
9998
0
    ImGuiContext& g = *GImGui;
9999
0
    if (window)
10000
0
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
10001
0
    else
10002
0
        g.WheelingWindowReleaseTimer = 0.0f;
10003
0
    if (g.WheelingWindow == window)
10004
0
        return;
10005
0
    IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
10006
0
    g.WheelingWindow = window;
10007
0
    g.WheelingWindowRefMousePos = g.IO.MousePos;
10008
0
    if (window == NULL)
10009
0
    {
10010
0
        g.WheelingWindowStartFrame = -1;
10011
0
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
10012
0
    }
10013
0
}
10014
10015
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
10016
3
{
10017
    // For each axis, find window in the hierarchy that may want to use scrolling
10018
3
    ImGuiContext& g = *GImGui;
10019
3
    ImGuiWindow* windows[2] = { NULL, NULL };
10020
9
    for (int axis = 0; axis < 2; axis++)
10021
6
        if (wheel[axis] != 0.0f)
10022
6
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
10023
0
            {
10024
                // Bubble up into parent window if:
10025
                // - a child window doesn't allow any scrolling.
10026
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
10027
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
10028
0
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
10029
0
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
10030
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
10031
0
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
10032
0
                    break; // select this window
10033
0
            }
10034
3
    if (windows[0] == NULL && windows[1] == NULL)
10035
0
        return NULL;
10036
10037
    // If there's only one window or only one axis then there's no ambiguity
10038
3
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
10039
3
        return windows[1] ? windows[1] : windows[0];
10040
10041
    // If candidate are different windows we need to decide which one to prioritize
10042
    // - First frame: only find a winner if one axis is zero.
10043
    // - Subsequent frames: only find a winner when one is more than the other.
10044
0
    if (g.WheelingWindowStartFrame == -1)
10045
0
        g.WheelingWindowStartFrame = g.FrameCount;
10046
0
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
10047
0
    {
10048
0
        g.WheelingWindowWheelRemainder = wheel;
10049
0
        return NULL;
10050
0
    }
10051
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
10052
0
}
10053
10054
// Called by NewFrame()
10055
void ImGui::UpdateMouseWheel()
10056
79.1k
{
10057
    // Reset the locked window if we move the mouse or after the timer elapses.
10058
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
10059
79.1k
    ImGuiContext& g = *GImGui;
10060
79.1k
    if (g.WheelingWindow != NULL)
10061
0
    {
10062
0
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
10063
0
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
10064
0
            g.WheelingWindowReleaseTimer = 0.0f;
10065
0
        if (g.WheelingWindowReleaseTimer <= 0.0f)
10066
0
            LockWheelingWindow(NULL, 0.0f);
10067
0
    }
10068
10069
79.1k
    ImVec2 wheel;
10070
79.1k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheelH : 0.0f;
10071
79.1k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheel : 0.0f;
10072
10073
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
10074
79.1k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
10075
79.1k
    if (!mouse_window || mouse_window->Collapsed)
10076
78.7k
        return;
10077
10078
    // Zoom / Scale window
10079
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
10080
325
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
10081
0
    {
10082
0
        LockWheelingWindow(mouse_window, wheel.y);
10083
0
        ImGuiWindow* window = mouse_window;
10084
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
10085
0
        const float scale = new_font_scale / window->FontWindowScale;
10086
0
        window->FontWindowScale = new_font_scale;
10087
0
        if (window == window->RootWindow)
10088
0
        {
10089
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
10090
0
            SetWindowPos(window, window->Pos + offset, 0);
10091
0
            window->Size = ImTrunc(window->Size * scale);
10092
0
            window->SizeFull = ImTrunc(window->SizeFull * scale);
10093
0
        }
10094
0
        return;
10095
0
    }
10096
325
    if (g.IO.KeyCtrl)
10097
0
        return;
10098
10099
    // Mouse wheel scrolling
10100
    // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
10101
325
    if (g.IO.MouseWheelRequestAxisSwap)
10102
0
        wheel = ImVec2(wheel.y, 0.0f);
10103
10104
    // Maintain a rough average of moving magnitude on both axises
10105
    // FIXME: should by based on wall clock time rather than frame-counter
10106
325
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
10107
325
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
10108
10109
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
10110
325
    wheel += g.WheelingWindowWheelRemainder;
10111
325
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
10112
325
    if (wheel.x == 0.0f && wheel.y == 0.0f)
10113
322
        return;
10114
10115
    // Mouse wheel scrolling: find target and apply
10116
    // - don't renew lock if axis doesn't apply on the window.
10117
    // - select a main axis when both axises are being moved.
10118
3
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
10119
3
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
10120
3
        {
10121
3
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
10122
3
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
10123
0
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
10124
3
            if (do_scroll[ImGuiAxis_X])
10125
0
            {
10126
0
                LockWheelingWindow(window, wheel.x);
10127
0
                float max_step = window->InnerRect.GetWidth() * 0.67f;
10128
0
                float scroll_step = ImTrunc(ImMin(2 * window->CalcFontSize(), max_step));
10129
0
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
10130
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
10131
0
            }
10132
3
            if (do_scroll[ImGuiAxis_Y])
10133
0
            {
10134
0
                LockWheelingWindow(window, wheel.y);
10135
0
                float max_step = window->InnerRect.GetHeight() * 0.67f;
10136
0
                float scroll_step = ImTrunc(ImMin(5 * window->CalcFontSize(), max_step));
10137
0
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
10138
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
10139
0
            }
10140
3
        }
10141
3
}
10142
10143
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
10144
0
{
10145
0
    ImGuiContext& g = *GImGui;
10146
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
10147
0
}
10148
10149
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
10150
0
{
10151
0
    ImGuiContext& g = *GImGui;
10152
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
10153
0
}
10154
10155
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10156
static const char* GetInputSourceName(ImGuiInputSource source)
10157
0
{
10158
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
10159
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
10160
0
    return input_source_names[source];
10161
0
}
10162
static const char* GetMouseSourceName(ImGuiMouseSource source)
10163
0
{
10164
0
    const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
10165
0
    IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
10166
0
    return mouse_source_names[source];
10167
0
}
10168
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
10169
0
{
10170
0
    ImGuiContext& g = *GImGui;
10171
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; }
10172
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; }
10173
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
10174
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
10175
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
10176
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
10177
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
10178
0
}
10179
#endif
10180
10181
// Process input queue
10182
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
10183
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
10184
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
10185
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
10186
79.1k
{
10187
79.1k
    ImGuiContext& g = *GImGui;
10188
79.1k
    ImGuiIO& io = g.IO;
10189
10190
    // Only trickle chars<>key when working with InputText()
10191
    // FIXME: InputText() could parse event trail?
10192
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
10193
79.1k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
10194
10195
79.1k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
10196
79.1k
    int  mouse_button_changed = 0x00;
10197
79.1k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
10198
10199
79.1k
    int event_n = 0;
10200
107k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
10201
39.7k
    {
10202
39.7k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
10203
39.7k
        if (e->Type == ImGuiInputEventType_MousePos)
10204
5.07k
        {
10205
5.07k
            if (g.IO.WantSetMousePos)
10206
0
                continue;
10207
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
10208
5.07k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
10209
5.07k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
10210
1.26k
                break;
10211
3.80k
            io.MousePos = event_pos;
10212
3.80k
            io.MouseSource = e->MousePos.MouseSource;
10213
3.80k
            mouse_moved = true;
10214
3.80k
        }
10215
34.7k
        else if (e->Type == ImGuiInputEventType_MouseButton)
10216
12.9k
        {
10217
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10218
12.9k
            const ImGuiMouseButton button = e->MouseButton.Button;
10219
12.9k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
10220
12.9k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
10221
4.75k
                break;
10222
8.21k
            if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
10223
0
                break;
10224
8.21k
            io.MouseDown[button] = e->MouseButton.Down;
10225
8.21k
            io.MouseSource = e->MouseButton.MouseSource;
10226
8.21k
            mouse_button_changed |= (1 << button);
10227
8.21k
        }
10228
21.7k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
10229
4.76k
        {
10230
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
10231
4.76k
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
10232
1.98k
                break;
10233
2.78k
            io.MouseWheelH += e->MouseWheel.WheelX;
10234
2.78k
            io.MouseWheel += e->MouseWheel.WheelY;
10235
2.78k
            io.MouseSource = e->MouseWheel.MouseSource;
10236
2.78k
            mouse_wheeled = true;
10237
2.78k
        }
10238
16.9k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
10239
0
        {
10240
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
10241
0
        }
10242
16.9k
        else if (e->Type == ImGuiInputEventType_Key)
10243
8.29k
        {
10244
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10245
8.29k
            if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10246
0
                continue;
10247
8.29k
            ImGuiKey key = e->Key.Key;
10248
8.29k
            IM_ASSERT(key != ImGuiKey_None);
10249
8.29k
            ImGuiKeyData* key_data = GetKeyData(key);
10250
8.29k
            const int key_data_index = (int)(key_data - g.IO.KeysData);
10251
8.29k
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
10252
1.69k
                break;
10253
6.59k
            key_data->Down = e->Key.Down;
10254
6.59k
            key_data->AnalogValue = e->Key.AnalogValue;
10255
6.59k
            key_changed = true;
10256
6.59k
            key_changed_mask.SetBit(key_data_index);
10257
10258
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
10259
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10260
            io.KeysDown[key_data_index] = key_data->Down;
10261
            if (io.KeyMap[key_data_index] != -1)
10262
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
10263
#endif
10264
6.59k
        }
10265
8.67k
        else if (e->Type == ImGuiInputEventType_Text)
10266
4.67k
        {
10267
4.67k
            if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10268
0
                continue;
10269
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
10270
4.67k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
10271
1.25k
                break;
10272
3.42k
            unsigned int c = e->Text.Char;
10273
3.42k
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
10274
3.42k
            if (trickle_interleaved_keys_and_text)
10275
0
                text_inputted = true;
10276
3.42k
        }
10277
3.99k
        else if (e->Type == ImGuiInputEventType_Focus)
10278
3.99k
        {
10279
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
10280
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
10281
3.99k
            const bool focus_lost = !e->AppFocused.Focused;
10282
3.99k
            io.AppFocusLost = focus_lost;
10283
3.99k
        }
10284
0
        else
10285
0
        {
10286
0
            IM_ASSERT(0 && "Unknown event!");
10287
0
        }
10288
39.7k
    }
10289
10290
    // Record trail (for domain-specific applications wanting to access a precise trail)
10291
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
10292
107k
    for (int n = 0; n < event_n; n++)
10293
28.8k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
10294
10295
    // [DEBUG]
10296
79.1k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10297
79.1k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
10298
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
10299
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
10300
79.1k
#endif
10301
10302
    // Remaining events will be processed on the next frame
10303
79.1k
    if (event_n == g.InputEventsQueue.Size)
10304
68.1k
        g.InputEventsQueue.resize(0);
10305
10.9k
    else
10306
10.9k
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
10307
10308
    // Clear buttons state when focus is lost
10309
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
10310
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
10311
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
10312
79.1k
    if (g.IO.AppFocusLost)
10313
3.92k
    {
10314
3.92k
        g.IO.ClearInputKeys();
10315
3.92k
        g.IO.ClearInputMouse();
10316
3.92k
    }
10317
79.1k
}
10318
10319
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
10320
0
{
10321
0
    if (!IsNamedKeyOrMod(key))
10322
0
        return ImGuiKeyOwner_NoOwner;
10323
10324
0
    ImGuiContext& g = *GImGui;
10325
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10326
0
    ImGuiID owner_id = owner_data->OwnerCurr;
10327
10328
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10329
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10330
0
            return ImGuiKeyOwner_NoOwner;
10331
10332
0
    return owner_id;
10333
0
}
10334
10335
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
10336
// TestKeyOwner(..., None) : (owner == None)
10337
// TestKeyOwner(..., Any)  : no owner test
10338
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
10339
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
10340
216k
{
10341
216k
    if (!IsNamedKeyOrMod(key))
10342
0
        return true;
10343
10344
216k
    ImGuiContext& g = *GImGui;
10345
216k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10346
110
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10347
2
            return false;
10348
10349
216k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10350
216k
    if (owner_id == ImGuiKeyOwner_Any)
10351
46.7k
        return (owner_data->LockThisFrame == false);
10352
10353
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
10354
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
10355
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
10356
169k
    if (owner_data->OwnerCurr != owner_id)
10357
1
    {
10358
1
        if (owner_data->LockThisFrame)
10359
0
            return false;
10360
1
        if (owner_data->OwnerCurr != ImGuiKeyOwner_NoOwner)
10361
0
            return false;
10362
1
    }
10363
10364
169k
    return true;
10365
169k
}
10366
10367
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
10368
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
10369
// - SetKeyOwner(..., None)              : clears owner
10370
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
10371
// - SetKeyOwner(..., Any or None, Lock) : set lock
10372
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
10373
1
{
10374
1
    ImGuiContext& g = *GImGui;
10375
1
    IM_ASSERT(IsNamedKeyOrMod(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
10376
1
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
10377
    //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
10378
10379
1
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10380
1
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
10381
10382
    // We cannot lock by default as it would likely break lots of legacy code.
10383
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
10384
1
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
10385
1
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
10386
1
}
10387
10388
// Rarely used helper
10389
void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10390
0
{
10391
0
    if (key_chord & ImGuiMod_Ctrl)      { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
10392
0
    if (key_chord & ImGuiMod_Shift)     { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
10393
0
    if (key_chord & ImGuiMod_Alt)       { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
10394
0
    if (key_chord & ImGuiMod_Super)     { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
10395
0
    if (key_chord & ~ImGuiMod_Mask_)    { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
10396
0
}
10397
10398
// This is more or less equivalent to:
10399
//   if (IsItemHovered() || IsItemActive())
10400
//       SetKeyOwner(key, GetItemID());
10401
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
10402
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
10403
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
10404
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
10405
0
{
10406
0
    ImGuiContext& g = *GImGui;
10407
0
    ImGuiID id = g.LastItemData.ID;
10408
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
10409
0
        return;
10410
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
10411
0
        flags |= ImGuiInputFlags_CondDefault_;
10412
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
10413
0
    {
10414
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
10415
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
10416
0
    }
10417
0
}
10418
10419
// This is the only public API until we expose owner_id versions of the API as replacements.
10420
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
10421
0
{
10422
0
    return IsKeyChordPressed(key_chord, ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10423
0
}
10424
10425
// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
10426
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10427
158k
{
10428
158k
    ImGuiContext& g = *GImGui;
10429
158k
    key_chord = FixupKeyChord(key_chord);
10430
158k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10431
158k
    if (g.IO.KeyMods != mods)
10432
158k
        return false;
10433
10434
    // Special storage location for mods
10435
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10436
0
    if (key == ImGuiKey_None)
10437
0
        key = ConvertSingleModFlagToKey(mods);
10438
0
    if (!IsKeyPressed(key, (flags & ImGuiInputFlags_RepeatMask_), owner_id))
10439
0
        return false;
10440
0
    return true;
10441
0
}
10442
10443
void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
10444
0
{
10445
0
    ImGuiContext& g = *GImGui;
10446
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasShortcut;
10447
0
    g.NextItemData.Shortcut = key_chord;
10448
0
    g.NextItemData.ShortcutFlags = flags;
10449
0
}
10450
10451
// Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData
10452
void ImGui::ItemHandleShortcut(ImGuiID id)
10453
0
{
10454
0
    ImGuiContext& g = *GImGui;
10455
0
    ImGuiInputFlags flags = g.NextItemData.ShortcutFlags;
10456
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetNextItemShortcut) == 0); // Passing flags not supported by SetNextItemShortcut()!
10457
10458
0
    if (g.LastItemData.InFlags & ImGuiItemFlags_Disabled)
10459
0
        return;
10460
0
    if (flags & ImGuiInputFlags_Tooltip)
10461
0
    {
10462
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasShortcut;
10463
0
        g.LastItemData.Shortcut = g.NextItemData.Shortcut;
10464
0
    }
10465
0
    if (!Shortcut(g.NextItemData.Shortcut, flags & ImGuiInputFlags_SupportedByShortcut, id) || g.NavActivateId != 0)
10466
0
        return;
10467
10468
    // FIXME: Generalize Activation queue?
10469
0
    g.NavActivateId = id; // Will effectively disable clipping.
10470
0
    g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
10471
    //if (g.ActiveId == 0 || g.ActiveId == id)
10472
0
    g.NavActivateDownId = g.NavActivatePressedId = id;
10473
0
    NavHighlightActivated(id);
10474
0
}
10475
10476
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
10477
0
{
10478
0
    return Shortcut(key_chord, flags, ImGuiKeyOwner_Any);
10479
0
}
10480
10481
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10482
158k
{
10483
158k
    ImGuiContext& g = *GImGui;
10484
    //IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id);
10485
10486
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
10487
158k
    if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
10488
0
        flags |= ImGuiInputFlags_RouteFocused;
10489
10490
    // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
10491
    // Effectively makes Shortcut() always input-owner aware.
10492
158k
    if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_NoOwner)
10493
0
        owner_id = GetRoutingIdFromOwnerId(owner_id);
10494
10495
158k
    if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
10496
0
        return false;
10497
10498
    // Submit route
10499
158k
    if (!SetShortcutRouting(key_chord, flags, owner_id))
10500
0
        return false;
10501
10502
    // Default repeat behavior for Shortcut()
10503
    // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
10504
158k
    if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
10505
158k
        flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
10506
10507
158k
    if (!IsKeyChordPressed(key_chord, flags, owner_id))
10508
158k
        return false;
10509
10510
    // Claim mods during the press
10511
0
    SetKeyOwnersForKeyChord(key_chord & ImGuiMod_Mask_, owner_id);
10512
10513
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
10514
0
    return true;
10515
158k
}
10516
10517
10518
//-----------------------------------------------------------------------------
10519
// [SECTION] ERROR CHECKING
10520
//-----------------------------------------------------------------------------
10521
10522
// Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues.
10523
// Called by IMGUI_CHECKVERSION().
10524
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
10525
// If this triggers you have mismatched headers and compiled code versions.
10526
// - It could be because of a build issue (using new headers with old compiled code)
10527
// - It could be because of mismatched configuration #define, compilation settings, packing pragma etc.
10528
//   THE CONFIGURATION SETTINGS MENTIONED IN imconfig.h MUST BE SET FOR ALL COMPILATION UNITS INVOLVED WITH DEAR IMGUI.
10529
//   Which is why it is required you put them in your imconfig file (and NOT only before including imgui.h).
10530
//   Otherwise it is possible that different compilation units would see different structure layout.
10531
//   If you don't want to modify imconfig.h you can use the IMGUI_USER_CONFIG define to change filename.
10532
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
10533
1
{
10534
1
    bool error = false;
10535
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
10536
1
    if (sz_io    != sizeof(ImGuiIO))    { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
10537
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
10538
1
    if (sz_vec2  != sizeof(ImVec2))     { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
10539
1
    if (sz_vec4  != sizeof(ImVec4))     { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
10540
1
    if (sz_vert  != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
10541
1
    if (sz_idx   != sizeof(ImDrawIdx))  { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
10542
1
    return !error;
10543
1
}
10544
10545
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
10546
// This is causing issues and ambiguity and we need to retire that.
10547
// See https://github.com/ocornut/imgui/issues/5548 for more details.
10548
// [Scenario 1]
10549
//  Previously this would make the window content size ~200x200:
10550
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
10551
//  Instead, please submit an item:
10552
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
10553
//  Alternative:
10554
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
10555
// [Scenario 2]
10556
//  For reference this is one of the issue what we aim to fix with this change:
10557
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
10558
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
10559
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
10560
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
10561
0
{
10562
0
    ImGuiContext& g = *GImGui;
10563
0
    ImGuiWindow* window = g.CurrentWindow;
10564
0
    IM_ASSERT(window->DC.IsSetPos);
10565
0
    window->DC.IsSetPos = false;
10566
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
10567
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
10568
0
        return;
10569
0
    if (window->SkipItems)
10570
0
        return;
10571
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
10572
#else
10573
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10574
#endif
10575
0
}
10576
10577
static void ImGui::ErrorCheckNewFrameSanityChecks()
10578
79.1k
{
10579
79.1k
    ImGuiContext& g = *GImGui;
10580
10581
    // Check user IM_ASSERT macro
10582
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
10583
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
10584
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
10585
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
10586
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
10587
79.1k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
10588
10589
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
10590
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
10591
#ifdef __EMSCRIPTEN__
10592
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
10593
        g.IO.DeltaTime = 0.00001f;
10594
#endif
10595
10596
    // Check user data
10597
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
10598
79.1k
    IM_ASSERT(g.Initialized);
10599
79.1k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
10600
79.1k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
10601
79.1k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
10602
79.1k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
10603
79.1k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
10604
79.1k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
10605
79.1k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
10606
79.1k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
10607
79.1k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
10608
79.1k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
10609
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10610
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
10611
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
10612
10613
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
10614
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
10615
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
10616
#endif
10617
10618
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
10619
79.1k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
10620
79.1k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10621
79.1k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
10622
79.1k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10623
10624
    // Perform simple checks: multi-viewport and platform windows support
10625
79.1k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
10626
1
    {
10627
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
10628
0
        {
10629
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
10630
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
10631
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
10632
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
10633
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
10634
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
10635
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
10636
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
10637
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
10638
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
10639
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
10640
0
        }
10641
1
        else
10642
1
        {
10643
            // Disable feature, our backends do not support it
10644
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
10645
1
        }
10646
10647
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
10648
1
        for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
10649
0
        {
10650
0
            IM_UNUSED(mon);
10651
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
10652
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
10653
0
            IM_ASSERT(mon.DpiScale != 0.0f);
10654
0
        }
10655
1
    }
10656
79.1k
}
10657
10658
static void ImGui::ErrorCheckEndFrameSanityChecks()
10659
79.1k
{
10660
79.1k
    ImGuiContext& g = *GImGui;
10661
10662
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
10663
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
10664
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
10665
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
10666
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
10667
    // while still correctly asserting on mid-frame key press events.
10668
79.1k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
10669
79.1k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
10670
79.1k
    IM_UNUSED(key_mods);
10671
10672
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
10673
    //ErrorCheckEndFrameRecover();
10674
10675
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
10676
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
10677
79.1k
    if (g.CurrentWindowStack.Size != 1)
10678
0
    {
10679
0
        if (g.CurrentWindowStack.Size > 1)
10680
0
        {
10681
0
            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
10682
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
10683
0
            IM_UNUSED(window);
10684
0
            while (g.CurrentWindowStack.Size > 1)
10685
0
                End();
10686
0
        }
10687
0
        else
10688
0
        {
10689
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
10690
0
        }
10691
0
    }
10692
10693
79.1k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
10694
79.1k
}
10695
10696
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
10697
// Must be called during or before EndFrame().
10698
// This is generally flawed as we are not necessarily End/Popping things in the right order.
10699
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
10700
// FIXME: Can't recover from interleaved BeginTabBar/Begin
10701
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10702
0
{
10703
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
10704
0
    ImGuiContext& g = *GImGui;
10705
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
10706
0
    {
10707
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
10708
0
        ImGuiWindow* window = g.CurrentWindow;
10709
0
        if (g.CurrentWindowStack.Size == 1)
10710
0
        {
10711
0
            IM_ASSERT(window->IsFallbackWindow);
10712
0
            break;
10713
0
        }
10714
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
10715
0
        {
10716
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
10717
0
            EndChild();
10718
0
        }
10719
0
        else
10720
0
        {
10721
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
10722
0
            End();
10723
0
        }
10724
0
    }
10725
0
}
10726
10727
// Must be called before End()/EndChild()
10728
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10729
0
{
10730
0
    ImGuiContext& g = *GImGui;
10731
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
10732
0
    {
10733
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
10734
0
        EndTable();
10735
0
    }
10736
10737
0
    ImGuiWindow* window = g.CurrentWindow;
10738
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
10739
0
    IM_ASSERT(window != NULL);
10740
0
    while (g.CurrentTabBar != NULL) //-V1044
10741
0
    {
10742
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
10743
0
        EndTabBar();
10744
0
    }
10745
0
    while (window->DC.TreeDepth > 0)
10746
0
    {
10747
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
10748
0
        TreePop();
10749
0
    }
10750
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
10751
0
    {
10752
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
10753
0
        EndGroup();
10754
0
    }
10755
0
    while (window->IDStack.Size > 1)
10756
0
    {
10757
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
10758
0
        PopID();
10759
0
    }
10760
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
10761
0
    {
10762
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
10763
0
        if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
10764
0
            EndDisabled();
10765
0
        else
10766
0
        {
10767
0
            EndDisabledOverrideReenable();
10768
0
            g.CurrentWindowStack.back().DisabledOverrideReenable = false;
10769
0
        }
10770
0
    }
10771
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
10772
0
    {
10773
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
10774
0
        PopStyleColor();
10775
0
    }
10776
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
10777
0
    {
10778
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
10779
0
        PopItemFlag();
10780
0
    }
10781
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
10782
0
    {
10783
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
10784
0
        PopStyleVar();
10785
0
    }
10786
0
    while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
10787
0
    {
10788
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
10789
0
        PopFont();
10790
0
    }
10791
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
10792
0
    {
10793
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
10794
0
        PopFocusScope();
10795
0
    }
10796
0
}
10797
10798
// Save current stack sizes for later compare
10799
void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
10800
169k
{
10801
169k
    ImGuiContext& g = *ctx;
10802
169k
    ImGuiWindow* window = g.CurrentWindow;
10803
169k
    SizeOfIDStack = (short)window->IDStack.Size;
10804
169k
    SizeOfColorStack = (short)g.ColorStack.Size;
10805
169k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10806
169k
    SizeOfFontStack = (short)g.FontStack.Size;
10807
169k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10808
169k
    SizeOfGroupStack = (short)g.GroupStack.Size;
10809
169k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10810
169k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10811
169k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
10812
169k
}
10813
10814
// Compare to detect usage errors
10815
void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
10816
169k
{
10817
169k
    ImGuiContext& g = *ctx;
10818
169k
    ImGuiWindow* window = g.CurrentWindow;
10819
169k
    IM_UNUSED(window);
10820
10821
    // Window stacks
10822
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
10823
169k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
10824
10825
    // Global stacks
10826
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
10827
169k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
10828
169k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
10829
169k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
10830
169k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
10831
169k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
10832
169k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
10833
169k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
10834
169k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
10835
169k
}
10836
10837
//-----------------------------------------------------------------------------
10838
// [SECTION] ITEM SUBMISSION
10839
//-----------------------------------------------------------------------------
10840
// - KeepAliveID()
10841
// - ItemAdd()
10842
//-----------------------------------------------------------------------------
10843
10844
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
10845
void ImGui::KeepAliveID(ImGuiID id)
10846
245k
{
10847
245k
    ImGuiContext& g = *GImGui;
10848
245k
    if (g.ActiveId == id)
10849
74
        g.ActiveIdIsAlive = id;
10850
245k
    if (g.ActiveIdPreviousFrame == id)
10851
74
        g.ActiveIdPreviousFrameIsAlive = true;
10852
245k
}
10853
10854
// Declare item bounding box for clipping and interaction.
10855
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10856
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10857
// THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
10858
IM_MSVC_RUNTIME_CHECKS_OFF
10859
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10860
257k
{
10861
257k
    ImGuiContext& g = *GImGui;
10862
257k
    ImGuiWindow* window = g.CurrentWindow;
10863
10864
    // Set item data
10865
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10866
257k
    g.LastItemData.ID = id;
10867
257k
    g.LastItemData.Rect = bb;
10868
257k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10869
257k
    g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10870
257k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10871
    // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
10872
10873
257k
    if (id != 0)
10874
245k
    {
10875
245k
        KeepAliveID(id);
10876
10877
        // Directional navigation processing
10878
        // Runs prior to clipping early-out
10879
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10880
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10881
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10882
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10883
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10884
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10885
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10886
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10887
245k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10888
166k
        {
10889
            // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
10890
166k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10891
166k
            if (g.NavId == id || g.NavAnyRequest)
10892
786
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10893
308
                    if (window == g.NavWindow || ((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened))
10894
308
                        NavProcessItem();
10895
166k
        }
10896
10897
245k
        if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasShortcut)
10898
0
            ItemHandleShortcut(id);
10899
245k
    }
10900
10901
    // Lightweight clear of SetNextItemXXX data.
10902
257k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10903
257k
    g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10904
10905
#ifdef IMGUI_ENABLE_TEST_ENGINE
10906
    if (id != 0)
10907
        IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10908
#endif
10909
10910
    // Clipping test
10911
    // (this is an inline copy of IsClippedEx() so we can reuse the is_rect_visible value, otherwise we'd do 'if (IsClippedEx(bb, id)) return false')
10912
    // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
10913
257k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10914
257k
    if (!is_rect_visible)
10915
20.2k
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
10916
20.2k
            if (!g.ItemUnclipByLog)
10917
20.2k
                return false;
10918
10919
    // [DEBUG]
10920
237k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10921
237k
    if (id != 0)
10922
234k
    {
10923
234k
        if (id == g.DebugLocateId)
10924
0
            DebugLocateItemResolveWithLastItem();
10925
10926
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10927
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10928
        // READ THE FAQ: https://dearimgui.com/faq
10929
234k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
10930
234k
    }
10931
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10932
    //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10933
    //    window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10934
237k
#endif
10935
10936
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10937
237k
    if (is_rect_visible)
10938
237k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10939
237k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
10940
3.34k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10941
237k
    return true;
10942
257k
}
10943
IM_MSVC_RUNTIME_CHECKS_RESTORE
10944
10945
//-----------------------------------------------------------------------------
10946
// [SECTION] LAYOUT
10947
//-----------------------------------------------------------------------------
10948
// - ItemSize()
10949
// - SameLine()
10950
// - GetCursorScreenPos()
10951
// - SetCursorScreenPos()
10952
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10953
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10954
// - GetCursorStartPos()
10955
// - Indent()
10956
// - Unindent()
10957
// - SetNextItemWidth()
10958
// - PushItemWidth()
10959
// - PushMultiItemsWidths()
10960
// - PopItemWidth()
10961
// - CalcItemWidth()
10962
// - CalcItemSize()
10963
// - GetTextLineHeight()
10964
// - GetTextLineHeightWithSpacing()
10965
// - GetFrameHeight()
10966
// - GetFrameHeightWithSpacing()
10967
// - GetContentRegionMax()
10968
// - GetContentRegionMaxAbs() [Internal]
10969
// - GetContentRegionAvail(),
10970
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
10971
// - BeginGroup()
10972
// - EndGroup()
10973
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
10974
//-----------------------------------------------------------------------------
10975
10976
// Advance cursor given item size for layout.
10977
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
10978
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
10979
// THIS IS IN THE PERFORMANCE CRITICAL PATH.
10980
IM_MSVC_RUNTIME_CHECKS_OFF
10981
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
10982
22.9k
{
10983
22.9k
    ImGuiContext& g = *GImGui;
10984
22.9k
    ImGuiWindow* window = g.CurrentWindow;
10985
22.9k
    if (window->SkipItems)
10986
0
        return;
10987
10988
    // We increase the height in this function to accommodate for baseline offset.
10989
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
10990
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
10991
22.9k
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
10992
10993
22.9k
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
10994
22.9k
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
10995
10996
    // Always align ourselves on pixel boundaries
10997
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
10998
22.9k
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
10999
22.9k
    window->DC.CursorPosPrevLine.y = line_y1;
11000
22.9k
    window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
11001
22.9k
    window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
11002
22.9k
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
11003
22.9k
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
11004
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
11005
11006
22.9k
    window->DC.PrevLineSize.y = line_height;
11007
22.9k
    window->DC.CurrLineSize.y = 0.0f;
11008
22.9k
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
11009
22.9k
    window->DC.CurrLineTextBaseOffset = 0.0f;
11010
22.9k
    window->DC.IsSameLine = window->DC.IsSetPos = false;
11011
11012
    // Horizontal layout mode
11013
22.9k
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
11014
0
        SameLine();
11015
22.9k
}
11016
IM_MSVC_RUNTIME_CHECKS_RESTORE
11017
11018
// Gets back to previous line and continue with horizontal layout
11019
//      offset_from_start_x == 0 : follow right after previous item
11020
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
11021
//      spacing_w < 0            : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
11022
//      spacing_w >= 0           : enforce spacing amount
11023
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
11024
0
{
11025
0
    ImGuiContext& g = *GImGui;
11026
0
    ImGuiWindow* window = g.CurrentWindow;
11027
0
    if (window->SkipItems)
11028
0
        return;
11029
11030
0
    if (offset_from_start_x != 0.0f)
11031
0
    {
11032
0
        if (spacing_w < 0.0f)
11033
0
            spacing_w = 0.0f;
11034
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
11035
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11036
0
    }
11037
0
    else
11038
0
    {
11039
0
        if (spacing_w < 0.0f)
11040
0
            spacing_w = g.Style.ItemSpacing.x;
11041
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
11042
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11043
0
    }
11044
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
11045
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
11046
0
    window->DC.IsSameLine = true;
11047
0
}
11048
11049
ImVec2 ImGui::GetCursorScreenPos()
11050
21.2k
{
11051
21.2k
    ImGuiWindow* window = GetCurrentWindowRead();
11052
21.2k
    return window->DC.CursorPos;
11053
21.2k
}
11054
11055
void ImGui::SetCursorScreenPos(const ImVec2& pos)
11056
0
{
11057
0
    ImGuiWindow* window = GetCurrentWindow();
11058
0
    window->DC.CursorPos = pos;
11059
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11060
0
    window->DC.IsSetPos = true;
11061
0
}
11062
11063
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
11064
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
11065
ImVec2 ImGui::GetCursorPos()
11066
0
{
11067
0
    ImGuiWindow* window = GetCurrentWindowRead();
11068
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
11069
0
}
11070
11071
float ImGui::GetCursorPosX()
11072
0
{
11073
0
    ImGuiWindow* window = GetCurrentWindowRead();
11074
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
11075
0
}
11076
11077
float ImGui::GetCursorPosY()
11078
0
{
11079
0
    ImGuiWindow* window = GetCurrentWindowRead();
11080
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
11081
0
}
11082
11083
void ImGui::SetCursorPos(const ImVec2& local_pos)
11084
0
{
11085
0
    ImGuiWindow* window = GetCurrentWindow();
11086
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
11087
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11088
0
    window->DC.IsSetPos = true;
11089
0
}
11090
11091
void ImGui::SetCursorPosX(float x)
11092
0
{
11093
0
    ImGuiWindow* window = GetCurrentWindow();
11094
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
11095
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
11096
0
    window->DC.IsSetPos = true;
11097
0
}
11098
11099
void ImGui::SetCursorPosY(float y)
11100
0
{
11101
0
    ImGuiWindow* window = GetCurrentWindow();
11102
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
11103
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
11104
0
    window->DC.IsSetPos = true;
11105
0
}
11106
11107
ImVec2 ImGui::GetCursorStartPos()
11108
0
{
11109
0
    ImGuiWindow* window = GetCurrentWindowRead();
11110
0
    return window->DC.CursorStartPos - window->Pos;
11111
0
}
11112
11113
void ImGui::Indent(float indent_w)
11114
0
{
11115
0
    ImGuiContext& g = *GImGui;
11116
0
    ImGuiWindow* window = GetCurrentWindow();
11117
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11118
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11119
0
}
11120
11121
void ImGui::Unindent(float indent_w)
11122
0
{
11123
0
    ImGuiContext& g = *GImGui;
11124
0
    ImGuiWindow* window = GetCurrentWindow();
11125
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11126
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11127
0
}
11128
11129
// Affect large frame+labels widgets only.
11130
void ImGui::SetNextItemWidth(float item_width)
11131
0
{
11132
0
    ImGuiContext& g = *GImGui;
11133
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
11134
0
    g.NextItemData.Width = item_width;
11135
0
}
11136
11137
// FIXME: Remove the == 0.0f behavior?
11138
void ImGui::PushItemWidth(float item_width)
11139
0
{
11140
0
    ImGuiContext& g = *GImGui;
11141
0
    ImGuiWindow* window = g.CurrentWindow;
11142
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
11143
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
11144
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
11145
0
}
11146
11147
void ImGui::PushMultiItemsWidths(int components, float w_full)
11148
0
{
11149
0
    ImGuiContext& g = *GImGui;
11150
0
    ImGuiWindow* window = g.CurrentWindow;
11151
0
    IM_ASSERT(components > 0);
11152
0
    const ImGuiStyle& style = g.Style;
11153
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
11154
0
    float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
11155
0
    float prev_split = w_items;
11156
0
    for (int i = components - 1; i > 0; i--)
11157
0
    {
11158
0
        float next_split = IM_TRUNC(w_items * i / components);
11159
0
        window->DC.ItemWidthStack.push_back(ImMax(prev_split - next_split, 1.0f));
11160
0
        prev_split = next_split;
11161
0
    }
11162
0
    window->DC.ItemWidth = ImMax(prev_split, 1.0f);
11163
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
11164
0
}
11165
11166
void ImGui::PopItemWidth()
11167
0
{
11168
0
    ImGuiWindow* window = GetCurrentWindow();
11169
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
11170
0
    window->DC.ItemWidthStack.pop_back();
11171
0
}
11172
11173
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
11174
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
11175
float ImGui::CalcItemWidth()
11176
0
{
11177
0
    ImGuiContext& g = *GImGui;
11178
0
    ImGuiWindow* window = g.CurrentWindow;
11179
0
    float w;
11180
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
11181
0
        w = g.NextItemData.Width;
11182
0
    else
11183
0
        w = window->DC.ItemWidth;
11184
0
    if (w < 0.0f)
11185
0
    {
11186
0
        float region_max_x = GetContentRegionMaxAbs().x;
11187
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
11188
0
    }
11189
0
    w = IM_TRUNC(w);
11190
0
    return w;
11191
0
}
11192
11193
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
11194
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
11195
// Note that only CalcItemWidth() is publicly exposed.
11196
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
11197
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
11198
11.4k
{
11199
11.4k
    ImGuiContext& g = *GImGui;
11200
11.4k
    ImGuiWindow* window = g.CurrentWindow;
11201
11202
11.4k
    ImVec2 region_max;
11203
11.4k
    if (size.x < 0.0f || size.y < 0.0f)
11204
0
        region_max = GetContentRegionMaxAbs();
11205
11206
11.4k
    if (size.x == 0.0f)
11207
2.97k
        size.x = default_w;
11208
8.51k
    else if (size.x < 0.0f)
11209
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
11210
11211
11.4k
    if (size.y == 0.0f)
11212
1.84k
        size.y = default_h;
11213
9.64k
    else if (size.y < 0.0f)
11214
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
11215
11216
11.4k
    return size;
11217
11.4k
}
11218
11219
float ImGui::GetTextLineHeight()
11220
0
{
11221
0
    ImGuiContext& g = *GImGui;
11222
0
    return g.FontSize;
11223
0
}
11224
11225
float ImGui::GetTextLineHeightWithSpacing()
11226
11.4k
{
11227
11.4k
    ImGuiContext& g = *GImGui;
11228
11.4k
    return g.FontSize + g.Style.ItemSpacing.y;
11229
11.4k
}
11230
11231
float ImGui::GetFrameHeight()
11232
56
{
11233
56
    ImGuiContext& g = *GImGui;
11234
56
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
11235
56
}
11236
11237
float ImGui::GetFrameHeightWithSpacing()
11238
0
{
11239
0
    ImGuiContext& g = *GImGui;
11240
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
11241
0
}
11242
11243
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
11244
11245
// FIXME: This is in window space (not screen space!).
11246
ImVec2 ImGui::GetContentRegionMax()
11247
0
{
11248
0
    ImGuiContext& g = *GImGui;
11249
0
    ImGuiWindow* window = g.CurrentWindow;
11250
0
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
11251
0
    return mx - window->Pos;
11252
0
}
11253
11254
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
11255
ImVec2 ImGui::GetContentRegionMaxAbs()
11256
11.4k
{
11257
11.4k
    ImGuiContext& g = *GImGui;
11258
11.4k
    ImGuiWindow* window = g.CurrentWindow;
11259
11.4k
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
11260
11.4k
    return mx;
11261
11.4k
}
11262
11263
ImVec2 ImGui::GetContentRegionAvail()
11264
11.4k
{
11265
11.4k
    ImGuiWindow* window = GImGui->CurrentWindow;
11266
11.4k
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
11267
11.4k
}
11268
11269
// In window space (not screen space!)
11270
ImVec2 ImGui::GetWindowContentRegionMin()
11271
0
{
11272
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11273
0
    return window->ContentRegionRect.Min - window->Pos;
11274
0
}
11275
11276
ImVec2 ImGui::GetWindowContentRegionMax()
11277
11.4k
{
11278
11.4k
    ImGuiWindow* window = GImGui->CurrentWindow;
11279
11.4k
    return window->ContentRegionRect.Max - window->Pos;
11280
11.4k
}
11281
11282
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
11283
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
11284
// FIXME-OPT: Could we safely early out on ->SkipItems?
11285
void ImGui::BeginGroup()
11286
0
{
11287
0
    ImGuiContext& g = *GImGui;
11288
0
    ImGuiWindow* window = g.CurrentWindow;
11289
11290
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
11291
0
    ImGuiGroupData& group_data = g.GroupStack.back();
11292
0
    group_data.WindowID = window->ID;
11293
0
    group_data.BackupCursorPos = window->DC.CursorPos;
11294
0
    group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
11295
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
11296
0
    group_data.BackupIndent = window->DC.Indent;
11297
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
11298
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
11299
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
11300
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
11301
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
11302
0
    group_data.BackupIsSameLine = window->DC.IsSameLine;
11303
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
11304
0
    group_data.EmitItem = true;
11305
11306
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
11307
0
    window->DC.Indent = window->DC.GroupOffset;
11308
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
11309
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
11310
0
    if (g.LogEnabled)
11311
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11312
0
}
11313
11314
void ImGui::EndGroup()
11315
0
{
11316
0
    ImGuiContext& g = *GImGui;
11317
0
    ImGuiWindow* window = g.CurrentWindow;
11318
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
11319
11320
0
    ImGuiGroupData& group_data = g.GroupStack.back();
11321
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
11322
11323
0
    if (window->DC.IsSetPos)
11324
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
11325
11326
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
11327
11328
0
    window->DC.CursorPos = group_data.BackupCursorPos;
11329
0
    window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
11330
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
11331
0
    window->DC.Indent = group_data.BackupIndent;
11332
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
11333
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
11334
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
11335
0
    window->DC.IsSameLine = group_data.BackupIsSameLine;
11336
0
    if (g.LogEnabled)
11337
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11338
11339
0
    if (!group_data.EmitItem)
11340
0
    {
11341
0
        g.GroupStack.pop_back();
11342
0
        return;
11343
0
    }
11344
11345
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
11346
0
    ItemSize(group_bb.GetSize());
11347
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
11348
11349
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
11350
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
11351
    // Also if you grep for LastItemId you'll notice it is only used in that context.
11352
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
11353
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
11354
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
11355
0
    if (group_contains_curr_active_id)
11356
0
        g.LastItemData.ID = g.ActiveId;
11357
0
    else if (group_contains_prev_active_id)
11358
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
11359
0
    g.LastItemData.Rect = group_bb;
11360
11361
    // Forward Hovered flag
11362
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
11363
0
    if (group_contains_curr_hovered_id)
11364
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
11365
11366
    // Forward Edited flag
11367
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
11368
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
11369
11370
    // Forward Deactivated flag
11371
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
11372
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
11373
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
11374
11375
0
    g.GroupStack.pop_back();
11376
0
    if (g.DebugShowGroupRects)
11377
0
        window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
11378
0
}
11379
11380
11381
//-----------------------------------------------------------------------------
11382
// [SECTION] SCROLLING
11383
//-----------------------------------------------------------------------------
11384
11385
// Helper to snap on edges when aiming at an item very close to the edge,
11386
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
11387
// When we refactor the scrolling API this may be configurable with a flag?
11388
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
11389
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
11390
0
{
11391
0
    if (target <= snap_min + snap_threshold)
11392
0
        return ImLerp(snap_min, target, center_ratio);
11393
0
    if (target >= snap_max - snap_threshold)
11394
0
        return ImLerp(target, snap_max, center_ratio);
11395
0
    return target;
11396
0
}
11397
11398
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
11399
169k
{
11400
169k
    ImVec2 scroll = window->Scroll;
11401
169k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
11402
509k
    for (int axis = 0; axis < 2; axis++)
11403
339k
    {
11404
339k
        if (window->ScrollTarget[axis] < FLT_MAX)
11405
5.60k
        {
11406
5.60k
            float center_ratio = window->ScrollTargetCenterRatio[axis];
11407
5.60k
            float scroll_target = window->ScrollTarget[axis];
11408
5.60k
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
11409
0
            {
11410
0
                float snap_min = 0.0f;
11411
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
11412
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
11413
0
            }
11414
5.60k
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
11415
5.60k
        }
11416
339k
        scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f));
11417
339k
        if (!window->Collapsed && !window->SkipItems)
11418
204k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
11419
339k
    }
11420
169k
    return scroll;
11421
169k
}
11422
11423
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
11424
0
{
11425
0
    ImGuiContext& g = *GImGui;
11426
0
    ImGuiWindow* window = g.CurrentWindow;
11427
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
11428
0
}
11429
11430
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11431
0
{
11432
0
    ScrollToRectEx(window, item_rect, flags);
11433
0
}
11434
11435
// Scroll to keep newly navigated item fully into view
11436
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11437
7
{
11438
7
    ImGuiContext& g = *GImGui;
11439
7
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
11440
7
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
11441
7
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
11442
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
11443
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
11444
11445
    // Check that only one behavior is selected per axis
11446
7
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
11447
7
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
11448
11449
    // Defaults
11450
7
    ImGuiScrollFlags in_flags = flags;
11451
7
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
11452
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
11453
7
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
11454
7
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
11455
11456
7
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
11457
7
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
11458
7
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11459
7
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11460
11461
7
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
11462
0
    {
11463
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
11464
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
11465
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
11466
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
11467
0
    }
11468
7
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
11469
0
    {
11470
0
        if (can_be_fully_visible_x)
11471
0
            SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
11472
0
        else
11473
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
11474
0
    }
11475
11476
7
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
11477
0
    {
11478
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
11479
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
11480
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
11481
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
11482
0
    }
11483
7
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
11484
0
    {
11485
0
        if (can_be_fully_visible_y)
11486
0
            SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
11487
0
        else
11488
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
11489
0
    }
11490
11491
7
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11492
7
    ImVec2 delta_scroll = next_scroll - window->Scroll;
11493
11494
    // Also scroll parent window to keep us into view if necessary
11495
7
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
11496
0
    {
11497
        // FIXME-SCROLL: May be an option?
11498
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
11499
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
11500
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
11501
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
11502
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
11503
0
    }
11504
11505
7
    return delta_scroll;
11506
7
}
11507
11508
float ImGui::GetScrollX()
11509
14.5k
{
11510
14.5k
    ImGuiWindow* window = GImGui->CurrentWindow;
11511
14.5k
    return window->Scroll.x;
11512
14.5k
}
11513
11514
float ImGui::GetScrollY()
11515
14.5k
{
11516
14.5k
    ImGuiWindow* window = GImGui->CurrentWindow;
11517
14.5k
    return window->Scroll.y;
11518
14.5k
}
11519
11520
float ImGui::GetScrollMaxX()
11521
0
{
11522
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11523
0
    return window->ScrollMax.x;
11524
0
}
11525
11526
float ImGui::GetScrollMaxY()
11527
0
{
11528
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11529
0
    return window->ScrollMax.y;
11530
0
}
11531
11532
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
11533
3.04k
{
11534
3.04k
    window->ScrollTarget.x = scroll_x;
11535
3.04k
    window->ScrollTargetCenterRatio.x = 0.0f;
11536
3.04k
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
11537
3.04k
}
11538
11539
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
11540
2.59k
{
11541
2.59k
    window->ScrollTarget.y = scroll_y;
11542
2.59k
    window->ScrollTargetCenterRatio.y = 0.0f;
11543
2.59k
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
11544
2.59k
}
11545
11546
void ImGui::SetScrollX(float scroll_x)
11547
3.04k
{
11548
3.04k
    ImGuiContext& g = *GImGui;
11549
3.04k
    SetScrollX(g.CurrentWindow, scroll_x);
11550
3.04k
}
11551
11552
void ImGui::SetScrollY(float scroll_y)
11553
2.55k
{
11554
2.55k
    ImGuiContext& g = *GImGui;
11555
2.55k
    SetScrollY(g.CurrentWindow, scroll_y);
11556
2.55k
}
11557
11558
// Note that a local position will vary depending on initial scroll value,
11559
// This is a little bit confusing so bear with us:
11560
//  - local_pos = (absolution_pos - window->Pos)
11561
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
11562
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
11563
//  - They mostly exist because of legacy API.
11564
// Following the rules above, when trying to work with scrolling code, consider that:
11565
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
11566
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
11567
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
11568
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
11569
0
{
11570
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
11571
0
    window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
11572
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
11573
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
11574
0
}
11575
11576
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
11577
0
{
11578
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
11579
0
    window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
11580
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
11581
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
11582
0
}
11583
11584
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
11585
0
{
11586
0
    ImGuiContext& g = *GImGui;
11587
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
11588
0
}
11589
11590
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
11591
0
{
11592
0
    ImGuiContext& g = *GImGui;
11593
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
11594
0
}
11595
11596
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
11597
void ImGui::SetScrollHereX(float center_x_ratio)
11598
0
{
11599
0
    ImGuiContext& g = *GImGui;
11600
0
    ImGuiWindow* window = g.CurrentWindow;
11601
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
11602
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
11603
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
11604
11605
    // Tweak: snap on edges when aiming at an item very close to the edge
11606
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
11607
0
}
11608
11609
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
11610
void ImGui::SetScrollHereY(float center_y_ratio)
11611
0
{
11612
0
    ImGuiContext& g = *GImGui;
11613
0
    ImGuiWindow* window = g.CurrentWindow;
11614
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
11615
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
11616
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
11617
11618
    // Tweak: snap on edges when aiming at an item very close to the edge
11619
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
11620
0
}
11621
11622
//-----------------------------------------------------------------------------
11623
// [SECTION] TOOLTIPS
11624
//-----------------------------------------------------------------------------
11625
11626
bool ImGui::BeginTooltip()
11627
0
{
11628
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11629
0
}
11630
11631
bool ImGui::BeginItemTooltip()
11632
0
{
11633
0
    if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11634
0
        return false;
11635
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11636
0
}
11637
11638
bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
11639
0
{
11640
0
    ImGuiContext& g = *GImGui;
11641
11642
0
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
11643
0
    {
11644
        // Drag and Drop tooltips are positioning differently than other tooltips:
11645
        // - offset visibility to increase visibility around mouse.
11646
        // - never clamp within outer viewport boundary.
11647
        // We call SetNextWindowPos() to enforce position and disable clamping.
11648
        // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
11649
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
11650
0
        ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
11651
0
        SetNextWindowPos(tooltip_pos);
11652
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
11653
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
11654
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
11655
0
    }
11656
11657
0
    char window_name[16];
11658
0
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
11659
0
    if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
11660
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
11661
0
            if (window->Active)
11662
0
            {
11663
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
11664
0
                SetWindowHiddenAndSkipItemsForCurrentFrame(window);
11665
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
11666
0
            }
11667
0
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
11668
0
    Begin(window_name, NULL, flags | extra_window_flags);
11669
    // 2023-03-09: Added bool return value to the API, but currently always returning true.
11670
    // If this ever returns false we need to update BeginDragDropSource() accordingly.
11671
    //if (!ret)
11672
    //    End();
11673
    //return ret;
11674
0
    return true;
11675
0
}
11676
11677
void ImGui::EndTooltip()
11678
0
{
11679
0
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
11680
0
    End();
11681
0
}
11682
11683
void ImGui::SetTooltip(const char* fmt, ...)
11684
0
{
11685
0
    va_list args;
11686
0
    va_start(args, fmt);
11687
0
    SetTooltipV(fmt, args);
11688
0
    va_end(args);
11689
0
}
11690
11691
void ImGui::SetTooltipV(const char* fmt, va_list args)
11692
0
{
11693
0
    if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
11694
0
        return;
11695
0
    TextV(fmt, args);
11696
0
    EndTooltip();
11697
0
}
11698
11699
// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
11700
// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
11701
void ImGui::SetItemTooltip(const char* fmt, ...)
11702
0
{
11703
0
    va_list args;
11704
0
    va_start(args, fmt);
11705
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11706
0
        SetTooltipV(fmt, args);
11707
0
    va_end(args);
11708
0
}
11709
11710
void ImGui::SetItemTooltipV(const char* fmt, va_list args)
11711
0
{
11712
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11713
0
        SetTooltipV(fmt, args);
11714
0
}
11715
11716
11717
//-----------------------------------------------------------------------------
11718
// [SECTION] POPUPS
11719
//-----------------------------------------------------------------------------
11720
11721
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
11722
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
11723
0
{
11724
0
    ImGuiContext& g = *GImGui;
11725
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
11726
0
    {
11727
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
11728
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
11729
0
        IM_ASSERT(id == 0);
11730
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11731
0
            return g.OpenPopupStack.Size > 0;
11732
0
        else
11733
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
11734
0
    }
11735
0
    else
11736
0
    {
11737
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11738
0
        {
11739
            // Return true if the popup is open anywhere in the popup stack
11740
0
            for (ImGuiPopupData& popup_data : g.OpenPopupStack)
11741
0
                if (popup_data.PopupId == id)
11742
0
                    return true;
11743
0
            return false;
11744
0
        }
11745
0
        else
11746
0
        {
11747
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
11748
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
11749
0
        }
11750
0
    }
11751
0
}
11752
11753
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
11754
0
{
11755
0
    ImGuiContext& g = *GImGui;
11756
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
11757
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
11758
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
11759
0
    return IsPopupOpen(id, popup_flags);
11760
0
}
11761
11762
// Also see FindBlockingModal(NULL)
11763
ImGuiWindow* ImGui::GetTopMostPopupModal()
11764
237k
{
11765
237k
    ImGuiContext& g = *GImGui;
11766
237k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11767
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11768
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
11769
0
                return popup;
11770
237k
    return NULL;
11771
237k
}
11772
11773
// See Demo->Stacked Modal to confirm what this is for.
11774
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
11775
79.1k
{
11776
79.1k
    ImGuiContext& g = *GImGui;
11777
79.1k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11778
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11779
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
11780
0
                return popup;
11781
79.1k
    return NULL;
11782
79.1k
}
11783
11784
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
11785
0
{
11786
0
    ImGuiContext& g = *GImGui;
11787
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11788
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
11789
0
    OpenPopupEx(id, popup_flags);
11790
0
}
11791
11792
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
11793
0
{
11794
0
    OpenPopupEx(id, popup_flags);
11795
0
}
11796
11797
// Mark popup as open (toggle toward open state).
11798
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
11799
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
11800
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
11801
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
11802
0
{
11803
0
    ImGuiContext& g = *GImGui;
11804
0
    ImGuiWindow* parent_window = g.CurrentWindow;
11805
0
    const int current_stack_size = g.BeginPopupStack.Size;
11806
11807
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
11808
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
11809
0
            return;
11810
11811
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
11812
0
    popup_ref.PopupId = id;
11813
0
    popup_ref.Window = NULL;
11814
0
    popup_ref.RestoreNavWindow = g.NavWindow;           // When popup closes focus may be restored to NavWindow (depend on window type).
11815
0
    popup_ref.OpenFrameCount = g.FrameCount;
11816
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
11817
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
11818
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
11819
11820
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
11821
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
11822
0
    {
11823
0
        g.OpenPopupStack.push_back(popup_ref);
11824
0
    }
11825
0
    else
11826
0
    {
11827
        // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
11828
        // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
11829
        // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
11830
        // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
11831
0
        bool keep_existing = false;
11832
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id)
11833
0
            if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
11834
0
                keep_existing = true;
11835
0
        if (keep_existing)
11836
0
        {
11837
            // No reopen
11838
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11839
0
        }
11840
0
        else
11841
0
        {
11842
            // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
11843
0
            ClosePopupToLevel(current_stack_size, true);
11844
0
            g.OpenPopupStack.push_back(popup_ref);
11845
0
        }
11846
11847
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11848
        // This is equivalent to what ClosePopupToLevel() does.
11849
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11850
        //    FocusWindow(parent_window);
11851
0
    }
11852
0
}
11853
11854
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11855
// This function closes any popups that are over 'ref_window'.
11856
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11857
5.02k
{
11858
5.02k
    ImGuiContext& g = *GImGui;
11859
5.02k
    if (g.OpenPopupStack.Size == 0)
11860
5.02k
        return;
11861
11862
    // Don't close our own child popup windows.
11863
    //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
11864
0
    int popup_count_to_keep = 0;
11865
0
    if (ref_window)
11866
0
    {
11867
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11868
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11869
0
        {
11870
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11871
0
            if (!popup.Window)
11872
0
                continue;
11873
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11874
11875
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11876
            // - Clicking/Focusing Window2 won't close Popup1:
11877
            //     Window -> Popup1 -> Window2(Ref)
11878
            // - Clicking/focusing Popup1 will close Popup2 and Popup3:
11879
            //     Window -> Popup1(Ref) -> Popup2 -> Popup3
11880
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
11881
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11882
            // We step through every popup from bottom to top to validate their position relative to reference window.
11883
0
            bool ref_window_is_descendent_of_popup = false;
11884
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11885
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11886
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
11887
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
11888
0
                    {
11889
0
                        ref_window_is_descendent_of_popup = true;
11890
0
                        break;
11891
0
                    }
11892
0
            if (!ref_window_is_descendent_of_popup)
11893
0
                break;
11894
0
        }
11895
0
    }
11896
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11897
0
    {
11898
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11899
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
11900
0
    }
11901
0
}
11902
11903
void ImGui::ClosePopupsExceptModals()
11904
0
{
11905
0
    ImGuiContext& g = *GImGui;
11906
11907
0
    int popup_count_to_keep;
11908
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11909
0
    {
11910
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11911
0
        if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11912
0
            break;
11913
0
    }
11914
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11915
0
        ClosePopupToLevel(popup_count_to_keep, true);
11916
0
}
11917
11918
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11919
0
{
11920
0
    ImGuiContext& g = *GImGui;
11921
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
11922
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11923
11924
    // Trim open popup stack
11925
0
    ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
11926
0
    g.OpenPopupStack.resize(remaining);
11927
11928
    // Restore focus (unless popup window was not yet submitted, and didn't have a chance to take focus anyhow. See #7325 for an edge case)
11929
0
    if (restore_focus_to_window_under_popup && prev_popup.Window)
11930
0
    {
11931
0
        ImGuiWindow* popup_window = prev_popup.Window;
11932
0
        ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
11933
0
        if (focus_window && !focus_window->WasActive)
11934
0
            FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11935
0
        else
11936
0
            FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11937
0
    }
11938
0
}
11939
11940
// Close the popup we have begin-ed into.
11941
void ImGui::CloseCurrentPopup()
11942
0
{
11943
0
    ImGuiContext& g = *GImGui;
11944
0
    int popup_idx = g.BeginPopupStack.Size - 1;
11945
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11946
0
        return;
11947
11948
    // Closing a menu closes its top-most parent popup (unless a modal)
11949
0
    while (popup_idx > 0)
11950
0
    {
11951
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11952
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11953
0
        bool close_parent = false;
11954
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11955
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11956
0
                close_parent = true;
11957
0
        if (!close_parent)
11958
0
            break;
11959
0
        popup_idx--;
11960
0
    }
11961
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11962
0
    ClosePopupToLevel(popup_idx, true);
11963
11964
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
11965
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
11966
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
11967
0
    if (ImGuiWindow* window = g.NavWindow)
11968
0
        window->DC.NavHideHighlightOneFrame = true;
11969
0
}
11970
11971
// Attention! BeginPopup() adds default flags when calling BeginPopupEx()!
11972
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags)
11973
0
{
11974
0
    ImGuiContext& g = *GImGui;
11975
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11976
0
    {
11977
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11978
0
        return false;
11979
0
    }
11980
11981
0
    char name[20];
11982
0
    if (extra_window_flags & ImGuiWindowFlags_ChildMenu)
11983
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuDepth); // Recycle windows based on depth
11984
0
    else
11985
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
11986
11987
0
    bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking);
11988
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
11989
0
        EndPopup();
11990
11991
    //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
11992
11993
0
    return is_open;
11994
0
}
11995
11996
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
11997
0
{
11998
0
    ImGuiContext& g = *GImGui;
11999
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
12000
0
    {
12001
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12002
0
        return false;
12003
0
    }
12004
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
12005
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
12006
0
    return BeginPopupEx(id, flags);
12007
0
}
12008
12009
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
12010
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
12011
// - *p_open set back to false in BeginPopupModal() when popup is not open.
12012
// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
12013
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
12014
0
{
12015
0
    ImGuiContext& g = *GImGui;
12016
0
    ImGuiWindow* window = g.CurrentWindow;
12017
0
    const ImGuiID id = window->GetID(name);
12018
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
12019
0
    {
12020
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12021
0
        if (p_open && *p_open)
12022
0
            *p_open = false;
12023
0
        return false;
12024
0
    }
12025
12026
    // Center modal windows by default for increased visibility
12027
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
12028
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
12029
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
12030
0
    {
12031
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
12032
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
12033
0
    }
12034
12035
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
12036
0
    const bool is_open = Begin(name, p_open, flags);
12037
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
12038
0
    {
12039
0
        EndPopup();
12040
0
        if (is_open)
12041
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
12042
0
        return false;
12043
0
    }
12044
0
    return is_open;
12045
0
}
12046
12047
void ImGui::EndPopup()
12048
0
{
12049
0
    ImGuiContext& g = *GImGui;
12050
0
    ImGuiWindow* window = g.CurrentWindow;
12051
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
12052
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
12053
12054
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
12055
0
    if (g.NavWindow == window)
12056
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
12057
12058
    // Child-popups don't need to be laid out
12059
0
    IM_ASSERT(g.WithinEndChild == false);
12060
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
12061
0
        g.WithinEndChild = true;
12062
0
    End();
12063
0
    g.WithinEndChild = false;
12064
0
}
12065
12066
// Helper to open a popup if mouse button is released over the item
12067
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
12068
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
12069
0
{
12070
0
    ImGuiContext& g = *GImGui;
12071
0
    ImGuiWindow* window = g.CurrentWindow;
12072
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12073
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12074
0
    {
12075
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
12076
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
12077
0
        OpenPopupEx(id, popup_flags);
12078
0
    }
12079
0
}
12080
12081
// This is a helper to handle the simplest case of associating one named popup to one given widget.
12082
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
12083
// - To create a popup with a specific identifier, pass it in str_id.
12084
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
12085
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
12086
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
12087
//   This is essentially the same as:
12088
//       id = str_id ? GetID(str_id) : GetItemID();
12089
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
12090
//       return BeginPopup(id);
12091
//   Which is essentially the same as:
12092
//       id = str_id ? GetID(str_id) : GetItemID();
12093
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
12094
//           OpenPopup(id);
12095
//       return BeginPopup(id);
12096
//   The main difference being that this is tweaked to avoid computing the ID twice.
12097
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
12098
0
{
12099
0
    ImGuiContext& g = *GImGui;
12100
0
    ImGuiWindow* window = g.CurrentWindow;
12101
0
    if (window->SkipItems)
12102
0
        return false;
12103
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
12104
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
12105
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12106
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12107
0
        OpenPopupEx(id, popup_flags);
12108
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12109
0
}
12110
12111
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
12112
0
{
12113
0
    ImGuiContext& g = *GImGui;
12114
0
    ImGuiWindow* window = g.CurrentWindow;
12115
0
    if (!str_id)
12116
0
        str_id = "window_context";
12117
0
    ImGuiID id = window->GetID(str_id);
12118
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12119
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12120
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
12121
0
            OpenPopupEx(id, popup_flags);
12122
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12123
0
}
12124
12125
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
12126
0
{
12127
0
    ImGuiContext& g = *GImGui;
12128
0
    ImGuiWindow* window = g.CurrentWindow;
12129
0
    if (!str_id)
12130
0
        str_id = "void_context";
12131
0
    ImGuiID id = window->GetID(str_id);
12132
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12133
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
12134
0
        if (GetTopMostPopupModal() == NULL)
12135
0
            OpenPopupEx(id, popup_flags);
12136
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12137
0
}
12138
12139
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
12140
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
12141
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
12142
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
12143
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
12144
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
12145
0
{
12146
0
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
12147
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
12148
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
12149
12150
    // Combo Box policy (we want a connecting edge)
12151
0
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
12152
0
    {
12153
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
12154
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
12155
0
        {
12156
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
12157
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
12158
0
                continue;
12159
0
            ImVec2 pos;
12160
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
12161
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
12162
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
12163
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
12164
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
12165
0
                continue;
12166
0
            *last_dir = dir;
12167
0
            return pos;
12168
0
        }
12169
0
    }
12170
12171
    // Tooltip and Default popup policy
12172
    // (Always first try the direction we used on the last frame, if any)
12173
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
12174
0
    {
12175
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
12176
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
12177
0
        {
12178
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
12179
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
12180
0
                continue;
12181
12182
0
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
12183
0
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
12184
12185
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
12186
0
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
12187
0
                continue;
12188
0
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
12189
0
                continue;
12190
12191
0
            ImVec2 pos;
12192
0
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
12193
0
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
12194
12195
            // Clamp top-left corner of popup
12196
0
            pos.x = ImMax(pos.x, r_outer.Min.x);
12197
0
            pos.y = ImMax(pos.y, r_outer.Min.y);
12198
12199
0
            *last_dir = dir;
12200
0
            return pos;
12201
0
        }
12202
0
    }
12203
12204
    // Fallback when not enough room:
12205
0
    *last_dir = ImGuiDir_None;
12206
12207
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
12208
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
12209
0
        return ref_pos + ImVec2(2, 2);
12210
12211
    // Otherwise try to keep within display
12212
0
    ImVec2 pos = ref_pos;
12213
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
12214
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
12215
0
    return pos;
12216
0
}
12217
12218
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
12219
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
12220
0
{
12221
0
    ImGuiContext& g = *GImGui;
12222
0
    ImRect r_screen;
12223
0
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
12224
0
    {
12225
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
12226
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
12227
0
        r_screen.Min = monitor.WorkPos;
12228
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
12229
0
    }
12230
0
    else
12231
0
    {
12232
        // Use the full viewport area (not work area) for popups
12233
0
        r_screen = window->Viewport->GetMainRect();
12234
0
    }
12235
0
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
12236
0
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
12237
0
    return r_screen;
12238
0
}
12239
12240
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
12241
0
{
12242
0
    ImGuiContext& g = *GImGui;
12243
12244
0
    ImRect r_outer = GetPopupAllowedExtentRect(window);
12245
0
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
12246
0
    {
12247
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
12248
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
12249
0
        ImGuiWindow* parent_window = window->ParentWindow;
12250
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
12251
0
        ImRect r_avoid;
12252
0
        if (parent_window->DC.MenuBarAppending)
12253
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
12254
0
        else
12255
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
12256
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
12257
0
    }
12258
0
    if (window->Flags & ImGuiWindowFlags_Popup)
12259
0
    {
12260
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
12261
0
    }
12262
0
    if (window->Flags & ImGuiWindowFlags_Tooltip)
12263
0
    {
12264
        // Position tooltip (always follows mouse + clamp within outer boundaries)
12265
        // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
12266
        // In theory we could handle both cases in same location, but requires a bit of shuffling as drag and drop tooltips are calling SetWindowPos() leading to 'window_pos_set_by_api' being set in Begin()
12267
0
        IM_ASSERT(g.CurrentWindow == window);
12268
0
        const float scale = g.Style.MouseCursorScale;
12269
0
        const ImVec2 ref_pos = NavCalcPreferredRefPos();
12270
0
        const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
12271
0
        ImRect r_avoid;
12272
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
12273
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
12274
0
        else
12275
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
12276
        //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
12277
0
        return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
12278
0
    }
12279
0
    IM_ASSERT(0);
12280
0
    return window->Pos;
12281
0
}
12282
12283
//-----------------------------------------------------------------------------
12284
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
12285
//-----------------------------------------------------------------------------
12286
12287
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
12288
// In our terminology those should be interchangeable, yet right now this is super confusing.
12289
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
12290
12291
void ImGui::SetNavWindow(ImGuiWindow* window)
12292
4.65k
{
12293
4.65k
    ImGuiContext& g = *GImGui;
12294
4.65k
    if (g.NavWindow != window)
12295
4.65k
    {
12296
4.65k
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
12297
4.65k
        g.NavWindow = window;
12298
4.65k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12299
4.65k
    }
12300
4.65k
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12301
4.65k
    NavUpdateAnyRequestFlag();
12302
4.65k
}
12303
12304
void ImGui::NavHighlightActivated(ImGuiID id)
12305
13
{
12306
13
    ImGuiContext& g = *GImGui;
12307
13
    g.NavHighlightActivatedId = id;
12308
13
    g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
12309
13
}
12310
12311
void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
12312
489
{
12313
489
    ImGuiContext& g = *GImGui;
12314
489
    g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
12315
489
}
12316
12317
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
12318
197
{
12319
197
    ImGuiContext& g = *GImGui;
12320
197
    IM_ASSERT(g.NavWindow != NULL);
12321
197
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
12322
197
    g.NavId = id;
12323
197
    g.NavLayer = nav_layer;
12324
197
    SetNavFocusScope(focus_scope_id);
12325
197
    g.NavWindow->NavLastIds[nav_layer] = id;
12326
197
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
12327
12328
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12329
197
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12330
197
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12331
197
}
12332
12333
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
12334
2
{
12335
2
    ImGuiContext& g = *GImGui;
12336
2
    IM_ASSERT(id != 0);
12337
12338
2
    if (g.NavWindow != window)
12339
2
       SetNavWindow(window);
12340
12341
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
12342
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
12343
2
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
12344
2
    g.NavId = id;
12345
2
    g.NavLayer = nav_layer;
12346
2
    SetNavFocusScope(g.CurrentFocusScopeId);
12347
2
    window->NavLastIds[nav_layer] = id;
12348
2
    if (g.LastItemData.ID == id)
12349
2
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12350
12351
2
    if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
12352
1
        g.NavDisableMouseHover = true;
12353
1
    else
12354
1
        g.NavDisableHighlight = true;
12355
12356
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12357
2
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12358
2
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12359
2
}
12360
12361
static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
12362
28
{
12363
28
    if (ImFabs(dx) > ImFabs(dy))
12364
0
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
12365
28
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
12366
28
}
12367
12368
static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
12369
56
{
12370
56
    if (cand_max < curr_min)
12371
24
        return cand_max - curr_min;
12372
32
    if (curr_max < cand_min)
12373
4
        return cand_min - curr_max;
12374
28
    return 0.0f;
12375
32
}
12376
12377
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
12378
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
12379
74
{
12380
74
    ImGuiContext& g = *GImGui;
12381
74
    ImGuiWindow* window = g.CurrentWindow;
12382
74
    if (g.NavLayer != window->DC.NavLayerCurrent)
12383
46
        return false;
12384
12385
    // FIXME: Those are not good variables names
12386
28
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
12387
28
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
12388
28
    g.NavScoringDebugCount++;
12389
12390
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
12391
28
    if (window->ParentWindow == g.NavWindow)
12392
0
    {
12393
0
        IM_ASSERT((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened);
12394
0
        if (!window->ClipRect.Overlaps(cand))
12395
0
            return false;
12396
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
12397
0
    }
12398
12399
    // Compute distance between boxes
12400
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
12401
28
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
12402
28
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
12403
28
    if (dby != 0.0f && dbx != 0.0f)
12404
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
12405
28
    float dist_box = ImFabs(dbx) + ImFabs(dby);
12406
12407
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
12408
28
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
12409
28
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
12410
28
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
12411
12412
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
12413
28
    ImGuiDir quadrant;
12414
28
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
12415
28
    if (dbx != 0.0f || dby != 0.0f)
12416
28
    {
12417
        // For non-overlapping boxes, use distance between boxes
12418
28
        dax = dbx;
12419
28
        day = dby;
12420
28
        dist_axial = dist_box;
12421
28
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
12422
28
    }
12423
0
    else if (dcx != 0.0f || dcy != 0.0f)
12424
0
    {
12425
        // For overlapping boxes with different centers, use distance between centers
12426
0
        dax = dcx;
12427
0
        day = dcy;
12428
0
        dist_axial = dist_center;
12429
0
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
12430
0
    }
12431
0
    else
12432
0
    {
12433
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
12434
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
12435
0
    }
12436
12437
28
    const ImGuiDir move_dir = g.NavMoveDir;
12438
#if IMGUI_DEBUG_NAV_SCORING
12439
    char buf[200];
12440
    if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
12441
    {
12442
        if (quadrant == move_dir)
12443
        {
12444
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
12445
            ImDrawList* draw_list = GetForegroundDrawList(window);
12446
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
12447
            draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
12448
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
12449
        }
12450
    }
12451
    const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
12452
    const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
12453
    if (debug_hovering || debug_tty)
12454
    {
12455
        ImFormatString(buf, IM_ARRAYSIZE(buf),
12456
            "d-box    (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial  (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
12457
            dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
12458
        if (debug_hovering)
12459
        {
12460
            ImDrawList* draw_list = GetForegroundDrawList(window);
12461
            draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
12462
            draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
12463
            draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
12464
            draw_list->AddText(cand.Max, ~0U, buf);
12465
        }
12466
        if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
12467
    }
12468
#endif
12469
12470
    // Is it in the quadrant we're interested in moving to?
12471
28
    bool new_best = false;
12472
28
    if (quadrant == move_dir)
12473
28
    {
12474
        // Does it beat the current best candidate?
12475
28
        if (dist_box < result->DistBox)
12476
28
        {
12477
28
            result->DistBox = dist_box;
12478
28
            result->DistCenter = dist_center;
12479
28
            return true;
12480
28
        }
12481
0
        if (dist_box == result->DistBox)
12482
0
        {
12483
            // Try using distance between center points to break ties
12484
0
            if (dist_center < result->DistCenter)
12485
0
            {
12486
0
                result->DistCenter = dist_center;
12487
0
                new_best = true;
12488
0
            }
12489
0
            else if (dist_center == result->DistCenter)
12490
0
            {
12491
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
12492
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
12493
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
12494
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
12495
0
                    new_best = true;
12496
0
            }
12497
0
        }
12498
0
    }
12499
12500
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
12501
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
12502
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
12503
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
12504
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
12505
0
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
12506
0
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
12507
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
12508
0
            {
12509
0
                result->DistAxial = dist_axial;
12510
0
                new_best = true;
12511
0
            }
12512
12513
0
    return new_best;
12514
28
}
12515
12516
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
12517
70
{
12518
70
    ImGuiContext& g = *GImGui;
12519
70
    ImGuiWindow* window = g.CurrentWindow;
12520
70
    result->Window = window;
12521
70
    result->ID = g.LastItemData.ID;
12522
70
    result->FocusScopeId = g.CurrentFocusScopeId;
12523
70
    result->InFlags = g.LastItemData.InFlags;
12524
70
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12525
70
    if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
12526
0
    {
12527
0
        IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12528
0
        result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12529
0
    }
12530
70
}
12531
12532
// True when current work location may be scrolled horizontally when moving left / right.
12533
// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
12534
void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
12535
260k
{
12536
260k
    ImGuiContext& g = *GImGui;
12537
260k
    ImGuiWindow* window = g.CurrentWindow;
12538
260k
    window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
12539
260k
}
12540
12541
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
12542
// This is called after LastItemData is set, but NextItemData is also still valid.
12543
static void ImGui::NavProcessItem()
12544
308
{
12545
308
    ImGuiContext& g = *GImGui;
12546
308
    ImGuiWindow* window = g.CurrentWindow;
12547
308
    const ImGuiID id = g.LastItemData.ID;
12548
308
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
12549
12550
    // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
12551
308
    if (window->DC.NavIsScrollPushableX == false)
12552
0
    {
12553
0
        g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12554
0
        g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12555
0
    }
12556
308
    const ImRect nav_bb = g.LastItemData.NavRect;
12557
12558
    // Process Init Request
12559
308
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
12560
42
    {
12561
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
12562
42
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
12563
42
        if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
12564
42
        {
12565
42
            NavApplyItemToResult(&g.NavInitResult);
12566
42
        }
12567
42
        if (candidate_for_nav_default_focus)
12568
0
        {
12569
0
            g.NavInitRequest = false; // Found a match, clear request
12570
0
            NavUpdateAnyRequestFlag();
12571
0
        }
12572
42
    }
12573
12574
    // Process Move Request (scoring for navigation)
12575
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
12576
308
    if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
12577
64
    {
12578
64
        if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
12579
64
        {
12580
64
            const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
12581
64
            if (is_tabbing)
12582
3
            {
12583
3
                NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
12584
3
            }
12585
61
            else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
12586
50
            {
12587
50
                ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
12588
50
                if (NavScoreItem(result))
12589
16
                    NavApplyItemToResult(result);
12590
12591
                // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
12592
50
                const float VISIBLE_RATIO = 0.70f;
12593
50
                if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
12594
24
                    if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
12595
24
                        if (NavScoreItem(&g.NavMoveResultLocalVisible))
12596
12
                            NavApplyItemToResult(&g.NavMoveResultLocalVisible);
12597
50
            }
12598
64
        }
12599
64
    }
12600
12601
    // Update information for currently focused/navigated item
12602
308
    if (g.NavId == id)
12603
200
    {
12604
200
        if (g.NavWindow != window)
12605
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
12606
200
        g.NavLayer = window->DC.NavLayerCurrent;
12607
200
        SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
12608
200
        g.NavFocusScopeId = g.CurrentFocusScopeId;
12609
200
        g.NavIdIsAlive = true;
12610
200
        if (g.LastItemData.InFlags & ImGuiItemFlags_HasSelectionUserData)
12611
0
        {
12612
0
            IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12613
0
            g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12614
0
        }
12615
200
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
12616
200
    }
12617
308
}
12618
12619
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
12620
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
12621
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
12622
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
12623
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
12624
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
12625
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
12626
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
12627
3
{
12628
3
    ImGuiContext& g = *GImGui;
12629
12630
3
    if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
12631
3
    {
12632
3
        if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
12633
3
            return;
12634
0
        if (g.NavFocusScopeId != g.CurrentFocusScopeId)
12635
0
            return;
12636
0
    }
12637
12638
    // - Can always land on an item when using API call.
12639
    // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
12640
    // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
12641
0
    bool can_stop;
12642
0
    if (move_flags & ImGuiNavMoveFlags_FocusApi)
12643
0
        can_stop = true;
12644
0
    else
12645
0
        can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
12646
12647
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
12648
0
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
12649
0
    if (g.NavTabbingDir == +1)
12650
0
    {
12651
        // Tab Forward or SetKeyboardFocusHere() with >= 0
12652
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0)
12653
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12654
0
        if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
12655
0
            NavMoveRequestResolveWithLastItem(result);
12656
0
        else if (g.NavId == id)
12657
0
            g.NavTabbingCounter = 1;
12658
0
    }
12659
0
    else if (g.NavTabbingDir == -1)
12660
0
    {
12661
        // Tab Backward
12662
0
        if (g.NavId == id)
12663
0
        {
12664
0
            if (result->ID)
12665
0
            {
12666
0
                g.NavMoveScoringItems = false;
12667
0
                NavUpdateAnyRequestFlag();
12668
0
            }
12669
0
        }
12670
0
        else if (can_stop)
12671
0
        {
12672
            // Keep applying until reaching NavId
12673
0
            NavApplyItemToResult(result);
12674
0
        }
12675
0
    }
12676
0
    else if (g.NavTabbingDir == 0)
12677
0
    {
12678
0
        if (can_stop && g.NavId == id)
12679
0
            NavMoveRequestResolveWithLastItem(result);
12680
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
12681
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12682
0
    }
12683
0
}
12684
12685
bool ImGui::NavMoveRequestButNoResultYet()
12686
6.07k
{
12687
6.07k
    ImGuiContext& g = *GImGui;
12688
6.07k
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
12689
6.07k
}
12690
12691
// FIXME: ScoringRect is not set
12692
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12693
176
{
12694
176
    ImGuiContext& g = *GImGui;
12695
176
    IM_ASSERT(g.NavWindow != NULL);
12696
12697
176
    if (move_flags & ImGuiNavMoveFlags_IsTabbing)
12698
82
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
12699
12700
176
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
12701
176
    g.NavMoveDir = move_dir;
12702
176
    g.NavMoveDirForDebug = move_dir;
12703
176
    g.NavMoveClipDir = clip_dir;
12704
176
    g.NavMoveFlags = move_flags;
12705
176
    g.NavMoveScrollFlags = scroll_flags;
12706
176
    g.NavMoveForwardToNextFrame = false;
12707
176
    g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
12708
176
    g.NavMoveResultLocal.Clear();
12709
176
    g.NavMoveResultLocalVisible.Clear();
12710
176
    g.NavMoveResultOther.Clear();
12711
176
    g.NavTabbingCounter = 0;
12712
176
    g.NavTabbingResultFirst.Clear();
12713
176
    NavUpdateAnyRequestFlag();
12714
176
}
12715
12716
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
12717
0
{
12718
0
    ImGuiContext& g = *GImGui;
12719
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
12720
0
    NavApplyItemToResult(result);
12721
0
    NavUpdateAnyRequestFlag();
12722
0
}
12723
12724
// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
12725
void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiNavTreeNodeData* tree_node_data)
12726
0
{
12727
0
    ImGuiContext& g = *GImGui;
12728
0
    g.NavMoveScoringItems = false;
12729
0
    g.LastItemData.ID = tree_node_data->ID;
12730
0
    g.LastItemData.InFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
12731
0
    g.LastItemData.NavRect = tree_node_data->NavRect;
12732
0
    NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
12733
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12734
0
    NavUpdateAnyRequestFlag();
12735
0
}
12736
12737
void ImGui::NavMoveRequestCancel()
12738
52
{
12739
52
    ImGuiContext& g = *GImGui;
12740
52
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12741
52
    NavUpdateAnyRequestFlag();
12742
52
}
12743
12744
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
12745
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12746
0
{
12747
0
    ImGuiContext& g = *GImGui;
12748
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
12749
0
    NavMoveRequestCancel();
12750
0
    g.NavMoveForwardToNextFrame = true;
12751
0
    g.NavMoveDir = move_dir;
12752
0
    g.NavMoveClipDir = clip_dir;
12753
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
12754
0
    g.NavMoveScrollFlags = scroll_flags;
12755
0
}
12756
12757
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
12758
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
12759
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
12760
0
{
12761
0
    ImGuiContext& g = *GImGui;
12762
0
    IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
12763
12764
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
12765
    // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
12766
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
12767
0
        g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
12768
0
}
12769
12770
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
12771
// This way we could find the last focused window among our children. It would be much less confusing this way?
12772
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
12773
3.84k
{
12774
3.84k
    ImGuiWindow* parent = nav_window;
12775
7.48k
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12776
3.63k
        parent = parent->ParentWindow;
12777
3.84k
    if (parent && parent != nav_window)
12778
3.63k
        parent->NavLastChildNavWindow = nav_window;
12779
3.84k
}
12780
12781
// Restore the last focused child.
12782
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
12783
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
12784
18
{
12785
18
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
12786
18
        return window->NavLastChildNavWindow;
12787
0
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
12788
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
12789
0
            return tab->Window;
12790
0
    return window;
12791
0
}
12792
12793
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
12794
60
{
12795
60
    ImGuiContext& g = *GImGui;
12796
60
    if (layer == ImGuiNavLayer_Main)
12797
18
    {
12798
18
        ImGuiWindow* prev_nav_window = g.NavWindow;
12799
18
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
12800
18
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12801
18
        if (prev_nav_window)
12802
18
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
12803
18
    }
12804
60
    ImGuiWindow* window = g.NavWindow;
12805
60
    if (window->NavLastIds[layer] != 0)
12806
1
    {
12807
1
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
12808
1
    }
12809
59
    else
12810
59
    {
12811
59
        g.NavLayer = layer;
12812
59
        NavInitWindow(window, true);
12813
59
    }
12814
60
}
12815
12816
void ImGui::NavRestoreHighlightAfterMove()
12817
159
{
12818
159
    ImGuiContext& g = *GImGui;
12819
159
    g.NavDisableHighlight = false;
12820
159
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
12821
159
}
12822
12823
static inline void ImGui::NavUpdateAnyRequestFlag()
12824
84.0k
{
12825
84.0k
    ImGuiContext& g = *GImGui;
12826
84.0k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
12827
84.0k
    if (g.NavAnyRequest)
12828
84.0k
        IM_ASSERT(g.NavWindow != NULL);
12829
84.0k
}
12830
12831
// This needs to be called before we submit any widget (aka in or before Begin)
12832
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
12833
72
{
12834
    // FIXME: ChildWindow test here is wrong for docking
12835
72
    ImGuiContext& g = *GImGui;
12836
72
    IM_ASSERT(window == g.NavWindow);
12837
12838
72
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
12839
0
    {
12840
0
        g.NavId = 0;
12841
0
        SetNavFocusScope(window->NavRootFocusScopeId);
12842
0
        return;
12843
0
    }
12844
12845
72
    bool init_for_nav = false;
12846
72
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
12847
72
        init_for_nav = true;
12848
72
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
12849
72
    if (init_for_nav)
12850
72
    {
12851
72
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
12852
72
        g.NavInitRequest = true;
12853
72
        g.NavInitRequestFromMove = false;
12854
72
        g.NavInitResult.ID = 0;
12855
72
        NavUpdateAnyRequestFlag();
12856
72
    }
12857
0
    else
12858
0
    {
12859
0
        g.NavId = window->NavLastIds[0];
12860
0
        SetNavFocusScope(window->NavRootFocusScopeId);
12861
0
    }
12862
72
}
12863
12864
static ImVec2 ImGui::NavCalcPreferredRefPos()
12865
0
{
12866
0
    ImGuiContext& g = *GImGui;
12867
0
    ImGuiWindow* window = g.NavWindow;
12868
0
    const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
12869
12870
    // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
12871
0
    if ((g.NavDisableHighlight || !g.NavDisableMouseHover || !window) && !activated_shortcut)
12872
0
    {
12873
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
12874
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
12875
        // In theory we could move that +1.0f offset in OpenPopupEx()
12876
0
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
12877
0
        return ImVec2(p.x + 1.0f, p.y);
12878
0
    }
12879
0
    else
12880
0
    {
12881
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
12882
0
        ImRect ref_rect;
12883
0
        if (activated_shortcut)
12884
0
            ref_rect = g.LastItemData.NavRect;
12885
0
        else
12886
0
            ref_rect = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
12887
12888
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
12889
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12890
0
        {
12891
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12892
0
            ref_rect.Translate(window->Scroll - next_scroll);
12893
0
        }
12894
0
        ImVec2 pos = ImVec2(ref_rect.Min.x + ImMin(g.Style.FramePadding.x * 4, ref_rect.GetWidth()), ref_rect.Max.y - ImMin(g.Style.FramePadding.y, ref_rect.GetHeight()));
12895
0
        ImGuiViewport* viewport = window->Viewport;
12896
0
        return ImTrunc(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
12897
0
    }
12898
0
}
12899
12900
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12901
0
{
12902
0
    ImGuiContext& g = *GImGui;
12903
0
    float repeat_delay, repeat_rate;
12904
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
12905
12906
0
    ImGuiKey key_less, key_more;
12907
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
12908
0
    {
12909
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12910
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12911
0
    }
12912
0
    else
12913
0
    {
12914
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12915
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12916
0
    }
12917
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
12918
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12919
0
        amount = 0.0f;
12920
0
    return amount;
12921
0
}
12922
12923
static void ImGui::NavUpdate()
12924
79.1k
{
12925
79.1k
    ImGuiContext& g = *GImGui;
12926
79.1k
    ImGuiIO& io = g.IO;
12927
12928
79.1k
    io.WantSetMousePos = false;
12929
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
12930
12931
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12932
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12933
79.1k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12934
79.1k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12935
79.1k
    if (nav_gamepad_active)
12936
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12937
0
            if (IsKeyDown(key))
12938
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
12939
79.1k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12940
79.1k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12941
79.1k
    if (nav_keyboard_active)
12942
79.1k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12943
553k
            if (IsKeyDown(key))
12944
42.2k
                g.NavInputSource = ImGuiInputSource_Keyboard;
12945
12946
    // Process navigation init request (select first/default focus)
12947
79.1k
    g.NavJustMovedToId = 0;
12948
79.1k
    if (g.NavInitResult.ID != 0)
12949
42
        NavInitRequestApplyResult();
12950
79.1k
    g.NavInitRequest = false;
12951
79.1k
    g.NavInitRequestFromMove = false;
12952
79.1k
    g.NavInitResult.ID = 0;
12953
12954
    // Process navigation move request
12955
79.1k
    if (g.NavMoveSubmitted)
12956
98
        NavMoveRequestApplyResult();
12957
79.1k
    g.NavTabbingCounter = 0;
12958
79.1k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12959
12960
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
12961
79.1k
    bool set_mouse_pos = false;
12962
79.1k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
12963
69
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
12964
67
            set_mouse_pos = true;
12965
79.1k
    g.NavMousePosDirty = false;
12966
79.1k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
12967
12968
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
12969
79.1k
    if (g.NavWindow)
12970
3.84k
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
12971
79.1k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
12972
72
        g.NavWindow->NavLastChildNavWindow = NULL;
12973
12974
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
12975
79.1k
    NavUpdateWindowing();
12976
12977
    // Set output flags for user application
12978
79.1k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
12979
79.1k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
12980
12981
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
12982
79.1k
    NavUpdateCancelRequest();
12983
12984
    // Process manual activation request
12985
79.1k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
12986
79.1k
    g.NavActivateFlags = ImGuiActivateFlags_None;
12987
79.1k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12988
298
    {
12989
298
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_NoOwner));
12990
298
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, 0, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, 0, ImGuiKeyOwner_NoOwner)));
12991
298
        const bool input_down = (nav_keyboard_active && (IsKeyDown(ImGuiKey_Enter, ImGuiKeyOwner_NoOwner) || IsKeyDown(ImGuiKey_KeypadEnter, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_NoOwner));
12992
298
        const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(ImGuiKey_Enter, 0, ImGuiKeyOwner_NoOwner) || IsKeyPressed(ImGuiKey_KeypadEnter, 0, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, 0, ImGuiKeyOwner_NoOwner)));
12993
298
        if (g.ActiveId == 0 && activate_pressed)
12994
13
        {
12995
13
            g.NavActivateId = g.NavId;
12996
13
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
12997
13
        }
12998
298
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
12999
0
        {
13000
0
            g.NavActivateId = g.NavId;
13001
0
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
13002
0
        }
13003
298
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
13004
24
            g.NavActivateDownId = g.NavId;
13005
298
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
13006
13
        {
13007
13
            g.NavActivatePressedId = g.NavId;
13008
13
            NavHighlightActivated(g.NavId);
13009
13
        }
13010
298
    }
13011
79.1k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
13012
0
        g.NavDisableHighlight = true;
13013
79.1k
    if (g.NavActivateId != 0)
13014
79.1k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
13015
13016
    // Highlight
13017
79.1k
    if (g.NavHighlightActivatedTimer > 0.0f)
13018
76
        g.NavHighlightActivatedTimer = ImMax(0.0f, g.NavHighlightActivatedTimer - io.DeltaTime);
13019
79.1k
    if (g.NavHighlightActivatedTimer == 0.0f)
13020
79.0k
        g.NavHighlightActivatedId = 0;
13021
13022
    // Process programmatic activation request
13023
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
13024
79.1k
    if (g.NavNextActivateId != 0)
13025
0
    {
13026
0
        g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
13027
0
        g.NavActivateFlags = g.NavNextActivateFlags;
13028
0
    }
13029
79.1k
    g.NavNextActivateId = 0;
13030
13031
    // Process move requests
13032
79.1k
    NavUpdateCreateMoveRequest();
13033
79.1k
    if (g.NavMoveDir == ImGuiDir_None)
13034
79.0k
        NavUpdateCreateTabbingRequest();
13035
79.1k
    NavUpdateAnyRequestFlag();
13036
79.1k
    g.NavIdIsAlive = false;
13037
13038
    // Scrolling
13039
79.1k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
13040
3.84k
    {
13041
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
13042
3.84k
        ImGuiWindow* window = g.NavWindow;
13043
3.84k
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
13044
3.84k
        const ImGuiDir move_dir = g.NavMoveDir;
13045
3.84k
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
13046
46
        {
13047
46
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
13048
8
                SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
13049
46
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
13050
38
                SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
13051
46
        }
13052
13053
        // *Normal* Manual scroll with LStick
13054
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
13055
3.84k
        if (nav_gamepad_active)
13056
0
        {
13057
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13058
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
13059
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
13060
0
                SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
13061
0
            if (scroll_dir.y != 0.0f)
13062
0
                SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
13063
0
        }
13064
3.84k
    }
13065
13066
    // Always prioritize mouse highlight if navigation is disabled
13067
79.1k
    if (!nav_keyboard_active && !nav_gamepad_active)
13068
0
    {
13069
0
        g.NavDisableHighlight = true;
13070
0
        g.NavDisableMouseHover = set_mouse_pos = false;
13071
0
    }
13072
13073
    // Update mouse position if requested
13074
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
13075
79.1k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
13076
0
        TeleportMousePos(NavCalcPreferredRefPos());
13077
13078
    // [DEBUG]
13079
79.1k
    g.NavScoringDebugCount = 0;
13080
#if IMGUI_DEBUG_NAV_RECTS
13081
    if (ImGuiWindow* debug_window = g.NavWindow)
13082
    {
13083
        ImDrawList* draw_list = GetForegroundDrawList(debug_window);
13084
        int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
13085
        //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
13086
    }
13087
#endif
13088
79.1k
}
13089
13090
void ImGui::NavInitRequestApplyResult()
13091
42
{
13092
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
13093
42
    ImGuiContext& g = *GImGui;
13094
42
    if (!g.NavWindow)
13095
12
        return;
13096
13097
30
    ImGuiNavItemData* result = &g.NavInitResult;
13098
30
    if (g.NavId != result->ID)
13099
29
    {
13100
29
        g.NavJustMovedToId = result->ID;
13101
29
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
13102
29
        g.NavJustMovedToKeyMods = 0;
13103
29
        g.NavJustMovedToIsTabbing = false;
13104
29
        g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
13105
29
    }
13106
13107
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
13108
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
13109
30
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
13110
30
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
13111
30
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
13112
30
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13113
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
13114
30
    if (g.NavInitRequestFromMove)
13115
0
        NavRestoreHighlightAfterMove();
13116
30
}
13117
13118
// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
13119
static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
13120
94
{
13121
    // Bias initial rect
13122
94
    ImGuiContext& g = *GImGui;
13123
94
    const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
13124
13125
    // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
13126
    // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
13127
    // - But each successful move sets new bias on one axis, only cleared when using mouse.
13128
94
    if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
13129
94
    {
13130
94
        if (preferred_pos_rel.x == FLT_MAX)
13131
48
            preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
13132
94
        if (preferred_pos_rel.y == FLT_MAX)
13133
54
            preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
13134
94
    }
13135
13136
    // Apply general bias on the other axis
13137
94
    if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
13138
75
        r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
13139
19
    else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
13140
19
        r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
13141
94
}
13142
13143
void ImGui::NavUpdateCreateMoveRequest()
13144
79.1k
{
13145
79.1k
    ImGuiContext& g = *GImGui;
13146
79.1k
    ImGuiIO& io = g.IO;
13147
79.1k
    ImGuiWindow* window = g.NavWindow;
13148
79.1k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13149
79.1k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13150
13151
79.1k
    if (g.NavMoveForwardToNextFrame && window != NULL)
13152
0
    {
13153
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
13154
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
13155
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
13156
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
13157
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
13158
0
    }
13159
79.1k
    else
13160
79.1k
    {
13161
        // Initiate directional inputs request
13162
79.1k
        g.NavMoveDir = ImGuiDir_None;
13163
79.1k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
13164
79.1k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
13165
79.1k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
13166
3.84k
        {
13167
3.84k
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
13168
3.84k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Left; }
13169
3.84k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Right; }
13170
3.84k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Up; }
13171
3.84k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Down; }
13172
3.84k
        }
13173
79.1k
        g.NavMoveClipDir = g.NavMoveDir;
13174
79.1k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
13175
79.1k
    }
13176
13177
    // Update PageUp/PageDown/Home/End scroll
13178
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
13179
79.1k
    float scoring_rect_offset_y = 0.0f;
13180
79.1k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
13181
3.77k
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
13182
79.1k
    if (scoring_rect_offset_y != 0.0f)
13183
21
    {
13184
21
        g.NavScoringNoClipRect = window->InnerRect;
13185
21
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
13186
21
    }
13187
13188
    // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
13189
#if IMGUI_DEBUG_NAV_SCORING
13190
    //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
13191
    //    g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
13192
    if (io.KeyCtrl)
13193
    {
13194
        if (g.NavMoveDir == ImGuiDir_None)
13195
            g.NavMoveDir = g.NavMoveDirForDebug;
13196
        g.NavMoveClipDir = g.NavMoveDir;
13197
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
13198
    }
13199
#endif
13200
13201
    // Submit
13202
79.1k
    g.NavMoveForwardToNextFrame = false;
13203
79.1k
    if (g.NavMoveDir != ImGuiDir_None)
13204
94
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
13205
13206
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
13207
79.1k
    if (g.NavMoveSubmitted && g.NavId == 0)
13208
60
    {
13209
60
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
13210
60
        g.NavInitRequest = g.NavInitRequestFromMove = true;
13211
60
        g.NavInitResult.ID = 0;
13212
60
        g.NavDisableHighlight = false;
13213
60
    }
13214
13215
    // When using gamepad, we project the reference nav bounding box into window visible area.
13216
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
13217
    // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
13218
79.1k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
13219
0
    {
13220
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
13221
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
13222
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
13223
13224
        // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
13225
        // Otherwise 'inner_rect_rel' would be off on the move result frame.
13226
0
        inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
13227
13228
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
13229
0
        {
13230
0
            IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
13231
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
13232
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
13233
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
13234
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
13235
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
13236
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
13237
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
13238
0
            g.NavId = 0;
13239
0
        }
13240
0
    }
13241
13242
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
13243
79.1k
    ImRect scoring_rect;
13244
79.1k
    if (window != NULL)
13245
3.84k
    {
13246
3.84k
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
13247
3.84k
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
13248
3.84k
        scoring_rect.TranslateY(scoring_rect_offset_y);
13249
3.84k
        if (g.NavMoveSubmitted)
13250
94
            NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
13251
3.84k
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
13252
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
13253
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
13254
3.84k
    }
13255
79.1k
    g.NavScoringRect = scoring_rect;
13256
79.1k
    g.NavScoringNoClipRect.Add(scoring_rect);
13257
79.1k
}
13258
13259
void ImGui::NavUpdateCreateTabbingRequest()
13260
79.0k
{
13261
79.0k
    ImGuiContext& g = *GImGui;
13262
79.0k
    ImGuiWindow* window = g.NavWindow;
13263
79.0k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
13264
79.0k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
13265
75.2k
        return;
13266
13267
3.75k
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
13268
3.75k
    if (!tab_pressed)
13269
3.67k
        return;
13270
13271
    // Initiate tabbing request
13272
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
13273
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
13274
82
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13275
82
    if (nav_keyboard_active)
13276
82
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
13277
0
    else
13278
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
13279
82
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
13280
82
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
13281
82
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
13282
82
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
13283
82
    g.NavTabbingCounter = -1;
13284
82
}
13285
13286
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
13287
void ImGui::NavMoveRequestApplyResult()
13288
98
{
13289
98
    ImGuiContext& g = *GImGui;
13290
#if IMGUI_DEBUG_NAV_SCORING
13291
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
13292
        return;
13293
#endif
13294
13295
    // Select which result to use
13296
98
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
13297
13298
    // Tabbing forward wrap
13299
98
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
13300
60
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
13301
0
            result = &g.NavTabbingResultFirst;
13302
13303
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
13304
98
    const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13305
98
    if (result == NULL)
13306
91
    {
13307
91
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13308
60
            g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
13309
91
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
13310
5
            NavRestoreHighlightAfterMove();
13311
91
        NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
13312
91
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
13313
91
        return;
13314
91
    }
13315
13316
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
13317
7
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
13318
7
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
13319
0
            result = &g.NavMoveResultLocalVisible;
13320
13321
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
13322
7
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
13323
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
13324
0
            result = &g.NavMoveResultOther;
13325
7
    IM_ASSERT(g.NavWindow && result->Window);
13326
13327
    // Scroll to keep newly navigated item fully into view.
13328
7
    if (g.NavLayer == ImGuiNavLayer_Main)
13329
7
    {
13330
7
        ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
13331
7
        ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
13332
13333
7
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
13334
0
        {
13335
            // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
13336
0
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
13337
0
            SetScrollY(result->Window, scroll_target);
13338
0
        }
13339
7
    }
13340
13341
7
    if (g.NavWindow != result->Window)
13342
0
    {
13343
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
13344
0
        g.NavWindow = result->Window;
13345
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13346
0
    }
13347
13348
    // Clear active id unless requested not to
13349
    // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction,
13350
    // so this is mostly provided as a gateway for further experiments (see #1418, #2890)
13351
7
    if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0)
13352
7
        ClearActiveID();
13353
13354
    // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
13355
    // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
13356
7
    if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
13357
7
    {
13358
7
        g.NavJustMovedToId = result->ID;
13359
7
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
13360
7
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
13361
7
        g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
13362
7
        g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
13363
        //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId);
13364
7
    }
13365
13366
    // Apply new NavID/Focus
13367
7
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
13368
7
    ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
13369
7
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
13370
7
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13371
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
13372
13373
    // Restore last preferred position for current axis
13374
    // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
13375
7
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
13376
7
    {
13377
7
        preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
13378
7
        g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
13379
7
    }
13380
13381
    // Tabbing: Activates Inputable, otherwise only Focus
13382
7
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
13383
0
        g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
13384
13385
    // Activate
13386
7
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
13387
0
    {
13388
0
        g.NavNextActivateId = result->ID;
13389
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
13390
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13391
0
            g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
13392
0
    }
13393
13394
    // Enable nav highlight
13395
7
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
13396
7
        NavRestoreHighlightAfterMove();
13397
7
}
13398
13399
// Process NavCancel input (to close a popup, get back to parent, clear focus)
13400
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
13401
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
13402
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
13403
static void ImGui::NavUpdateCancelRequest()
13404
79.1k
{
13405
79.1k
    ImGuiContext& g = *GImGui;
13406
79.1k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13407
79.1k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13408
79.1k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, 0, ImGuiKeyOwner_NoOwner)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, 0, ImGuiKeyOwner_NoOwner)))
13409
78.0k
        return;
13410
13411
1.09k
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
13412
1.09k
    if (g.ActiveId != 0)
13413
0
    {
13414
0
        ClearActiveID();
13415
0
    }
13416
1.09k
    else if (g.NavLayer != ImGuiNavLayer_Main)
13417
0
    {
13418
        // Leave the "menu" layer
13419
0
        NavRestoreLayer(ImGuiNavLayer_Main);
13420
0
        NavRestoreHighlightAfterMove();
13421
0
    }
13422
1.09k
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
13423
87
    {
13424
        // Exit child window
13425
87
        ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
13426
87
        ImGuiWindow* parent_window = child_window->ParentWindow;
13427
87
        IM_ASSERT(child_window->ChildId != 0);
13428
87
        FocusWindow(parent_window);
13429
87
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_window->Rect()));
13430
87
        NavRestoreHighlightAfterMove();
13431
87
    }
13432
1.00k
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
13433
0
    {
13434
        // Close open popup/menu
13435
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
13436
0
    }
13437
1.00k
    else
13438
1.00k
    {
13439
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
13440
1.00k
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
13441
2
            g.NavWindow->NavLastIds[0] = 0;
13442
1.00k
        g.NavId = 0;
13443
1.00k
    }
13444
1.09k
}
13445
13446
// Handle PageUp/PageDown/Home/End keys
13447
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
13448
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
13449
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
13450
static float ImGui::NavUpdatePageUpPageDown()
13451
3.77k
{
13452
3.77k
    ImGuiContext& g = *GImGui;
13453
3.77k
    ImGuiWindow* window = g.NavWindow;
13454
3.77k
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
13455
0
        return 0.0f;
13456
13457
3.77k
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_NoOwner);
13458
3.77k
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_NoOwner);
13459
3.77k
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
13460
3.77k
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
13461
3.77k
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
13462
3.44k
        return 0.0f;
13463
13464
338
    if (g.NavLayer != ImGuiNavLayer_Main)
13465
0
        NavRestoreLayer(ImGuiNavLayer_Main);
13466
13467
338
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
13468
207
    {
13469
        // Fallback manual-scroll when window has no navigable item
13470
207
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
13471
0
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
13472
207
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
13473
1
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
13474
206
        else if (home_pressed)
13475
0
            SetScrollY(window, 0.0f);
13476
206
        else if (end_pressed)
13477
0
            SetScrollY(window, window->ScrollMax.y);
13478
207
    }
13479
131
    else
13480
131
    {
13481
131
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
13482
131
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
13483
131
        float nav_scoring_rect_offset_y = 0.0f;
13484
131
        if (IsKeyPressed(ImGuiKey_PageUp, true))
13485
8
        {
13486
8
            nav_scoring_rect_offset_y = -page_offset_y;
13487
8
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
13488
8
            g.NavMoveClipDir = ImGuiDir_Up;
13489
8
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13490
8
        }
13491
123
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
13492
13
        {
13493
13
            nav_scoring_rect_offset_y = +page_offset_y;
13494
13
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
13495
13
            g.NavMoveClipDir = ImGuiDir_Down;
13496
13
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13497
13
        }
13498
110
        else if (home_pressed)
13499
4
        {
13500
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
13501
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
13502
            // Preserve current horizontal position if we have any.
13503
4
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
13504
4
            if (nav_rect_rel.IsInverted())
13505
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13506
4
            g.NavMoveDir = ImGuiDir_Down;
13507
4
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13508
            // FIXME-NAV: MoveClipDir left to _None, intentional?
13509
4
        }
13510
106
        else if (end_pressed)
13511
0
        {
13512
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
13513
0
            if (nav_rect_rel.IsInverted())
13514
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13515
0
            g.NavMoveDir = ImGuiDir_Up;
13516
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13517
            // FIXME-NAV: MoveClipDir left to _None, intentional?
13518
0
        }
13519
131
        return nav_scoring_rect_offset_y;
13520
131
    }
13521
207
    return 0.0f;
13522
338
}
13523
13524
static void ImGui::NavEndFrame()
13525
79.1k
{
13526
79.1k
    ImGuiContext& g = *GImGui;
13527
13528
    // Show CTRL+TAB list window
13529
79.1k
    if (g.NavWindowingTarget != NULL)
13530
0
        NavUpdateWindowingOverlay();
13531
13532
    // Perform wrap-around in menus
13533
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
13534
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
13535
79.1k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
13536
0
        NavUpdateCreateWrappingRequest();
13537
79.1k
}
13538
13539
static void ImGui::NavUpdateCreateWrappingRequest()
13540
0
{
13541
0
    ImGuiContext& g = *GImGui;
13542
0
    ImGuiWindow* window = g.NavWindow;
13543
13544
0
    bool do_forward = false;
13545
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
13546
0
    ImGuiDir clip_dir = g.NavMoveDir;
13547
13548
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
13549
    //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13550
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13551
0
    {
13552
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
13553
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
13554
0
        {
13555
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
13556
0
            clip_dir = ImGuiDir_Up;
13557
0
        }
13558
0
        do_forward = true;
13559
0
    }
13560
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13561
0
    {
13562
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
13563
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
13564
0
        {
13565
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
13566
0
            clip_dir = ImGuiDir_Down;
13567
0
        }
13568
0
        do_forward = true;
13569
0
    }
13570
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13571
0
    {
13572
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
13573
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
13574
0
        {
13575
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
13576
0
            clip_dir = ImGuiDir_Left;
13577
0
        }
13578
0
        do_forward = true;
13579
0
    }
13580
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13581
0
    {
13582
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
13583
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
13584
0
        {
13585
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
13586
0
            clip_dir = ImGuiDir_Right;
13587
0
        }
13588
0
        do_forward = true;
13589
0
    }
13590
0
    if (!do_forward)
13591
0
        return;
13592
0
    window->NavRectRel[g.NavLayer] = bb_rel;
13593
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
13594
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
13595
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
13596
0
}
13597
13598
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
13599
0
{
13600
0
    ImGuiContext& g = *GImGui;
13601
0
    IM_UNUSED(g);
13602
0
    int order = window->FocusOrder;
13603
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
13604
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
13605
0
    return order;
13606
0
}
13607
13608
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
13609
0
{
13610
0
    ImGuiContext& g = *GImGui;
13611
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
13612
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
13613
0
            return g.WindowsFocusOrder[i];
13614
0
    return NULL;
13615
0
}
13616
13617
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
13618
0
{
13619
0
    ImGuiContext& g = *GImGui;
13620
0
    IM_ASSERT(g.NavWindowingTarget);
13621
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
13622
0
        return;
13623
13624
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
13625
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
13626
0
    if (!window_target)
13627
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
13628
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
13629
0
    {
13630
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
13631
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13632
0
    }
13633
0
    g.NavWindowingToggleLayer = false;
13634
0
}
13635
13636
// Windowing management mode
13637
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
13638
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
13639
static void ImGui::NavUpdateWindowing()
13640
79.1k
{
13641
79.1k
    ImGuiContext& g = *GImGui;
13642
79.1k
    ImGuiIO& io = g.IO;
13643
13644
79.1k
    ImGuiWindow* apply_focus_window = NULL;
13645
79.1k
    bool apply_toggle_layer = false;
13646
13647
79.1k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
13648
79.1k
    bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
13649
79.1k
    if (!allow_windowing)
13650
0
        g.NavWindowingTarget = NULL;
13651
13652
    // Fade out
13653
79.1k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
13654
0
    {
13655
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
13656
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
13657
0
            g.NavWindowingTargetAnim = NULL;
13658
0
    }
13659
13660
    // Start CTRL+Tab or Square+L/R window selection
13661
    // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
13662
79.1k
    const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
13663
79.1k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13664
79.1k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13665
79.1k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
13666
79.1k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
13667
79.1k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_None);
13668
79.1k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
13669
79.1k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
13670
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
13671
0
        {
13672
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
13673
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
13674
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13675
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
13676
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
13677
13678
            // Manually register ownership of our mods. Using a global route in the Shortcut() calls instead would probably be correct but may have more side-effects.
13679
0
            if (keyboard_next_window || keyboard_prev_window)
13680
0
                SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
13681
0
        }
13682
13683
    // Gamepad update
13684
79.1k
    g.NavWindowingTimer += io.DeltaTime;
13685
79.1k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
13686
0
    {
13687
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
13688
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
13689
13690
        // Select window to focus
13691
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
13692
0
        if (focus_change_dir != 0)
13693
0
        {
13694
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
13695
0
            g.NavWindowingHighlightAlpha = 1.0f;
13696
0
        }
13697
13698
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
13699
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
13700
0
        {
13701
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
13702
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
13703
0
                apply_toggle_layer = true;
13704
0
            else if (!g.NavWindowingToggleLayer)
13705
0
                apply_focus_window = g.NavWindowingTarget;
13706
0
            g.NavWindowingTarget = NULL;
13707
0
        }
13708
0
    }
13709
13710
    // Keyboard: Focus
13711
79.1k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
13712
0
    {
13713
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
13714
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
13715
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
13716
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
13717
0
        if (keyboard_next_window || keyboard_prev_window)
13718
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
13719
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
13720
0
            apply_focus_window = g.NavWindowingTarget;
13721
0
    }
13722
13723
    // Keyboard: Press and Release ALT to toggle menu layer
13724
79.1k
    const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
13725
79.1k
    for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
13726
158k
        if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, 0, ImGuiKeyOwner_NoOwner))
13727
954
        {
13728
954
            g.NavWindowingToggleLayer = true;
13729
954
            g.NavWindowingToggleKey = windowing_toggle_key;
13730
954
            g.NavInputSource = ImGuiInputSource_Keyboard;
13731
954
            break;
13732
954
        }
13733
79.1k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
13734
4.55k
    {
13735
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
13736
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
13737
        // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl).
13738
        // We cancel toggling nav layer if an owner has claimed the key.
13739
4.55k
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
13740
95
            g.NavWindowingToggleLayer = false;
13741
4.55k
        if (TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_NoOwner) == false || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_NoOwner) == false)
13742
0
            g.NavWindowingToggleLayer = false;
13743
13744
        // Apply layer toggle on Alt release
13745
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
13746
4.55k
        if (IsKeyReleased(g.NavWindowingToggleKey) && g.NavWindowingToggleLayer)
13747
638
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
13748
638
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
13749
633
                    apply_toggle_layer = true;
13750
4.55k
        if (!IsKeyDown(g.NavWindowingToggleKey))
13751
911
            g.NavWindowingToggleLayer = false;
13752
4.55k
    }
13753
13754
    // Move window
13755
79.1k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
13756
0
    {
13757
0
        ImVec2 nav_move_dir;
13758
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
13759
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
13760
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
13761
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13762
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
13763
0
        {
13764
0
            const float NAV_MOVE_SPEED = 800.0f;
13765
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
13766
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
13767
0
            g.NavDisableMouseHover = true;
13768
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
13769
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
13770
0
            {
13771
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
13772
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
13773
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
13774
0
            }
13775
0
        }
13776
0
    }
13777
13778
    // Apply final focus
13779
79.1k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
13780
0
    {
13781
        // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
13782
        // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
13783
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
13784
0
        ClearActiveID();
13785
0
        NavRestoreHighlightAfterMove();
13786
0
        ClosePopupsOverWindow(apply_focus_window, false);
13787
0
        FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
13788
0
        apply_focus_window = g.NavWindow;
13789
0
        if (apply_focus_window->NavLastIds[0] == 0)
13790
0
            NavInitWindow(apply_focus_window, false);
13791
13792
        // If the window has ONLY a menu layer (no main layer), select it directly
13793
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
13794
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
13795
        // the target window as already been previewed once.
13796
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
13797
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
13798
        // won't be valid.
13799
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
13800
0
            g.NavLayer = ImGuiNavLayer_Menu;
13801
13802
        // Request OS level focus
13803
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
13804
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
13805
0
    }
13806
79.1k
    if (apply_focus_window)
13807
0
        g.NavWindowingTarget = NULL;
13808
13809
    // Apply menu/layer toggle
13810
79.1k
    if (apply_toggle_layer && g.NavWindow)
13811
60
    {
13812
60
        ClearActiveID();
13813
13814
        // Move to parent menu if necessary
13815
60
        ImGuiWindow* new_nav_window = g.NavWindow;
13816
102
        while (new_nav_window->ParentWindow
13817
102
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
13818
102
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
13819
102
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13820
42
            new_nav_window = new_nav_window->ParentWindow;
13821
60
        if (new_nav_window != g.NavWindow)
13822
42
        {
13823
42
            ImGuiWindow* old_nav_window = g.NavWindow;
13824
42
            FocusWindow(new_nav_window);
13825
42
            new_nav_window->NavLastChildNavWindow = old_nav_window;
13826
42
        }
13827
13828
        // Toggle layer
13829
60
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
13830
60
        if (new_nav_layer != g.NavLayer)
13831
60
        {
13832
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
13833
60
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
13834
60
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
13835
42
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
13836
60
            NavRestoreLayer(new_nav_layer);
13837
60
            NavRestoreHighlightAfterMove();
13838
60
        }
13839
60
    }
13840
79.1k
}
13841
13842
// Window has already passed the IsWindowNavFocusable()
13843
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
13844
0
{
13845
0
    if (window->Flags & ImGuiWindowFlags_Popup)
13846
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
13847
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
13848
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
13849
0
    if (window->DockNodeAsHost)
13850
0
        return "(Dock node)"; // Not normally shown to user.
13851
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
13852
0
}
13853
13854
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
13855
void ImGui::NavUpdateWindowingOverlay()
13856
0
{
13857
0
    ImGuiContext& g = *GImGui;
13858
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
13859
13860
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
13861
0
        return;
13862
13863
0
    if (g.NavWindowingListWindow == NULL)
13864
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
13865
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
13866
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
13867
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
13868
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
13869
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
13870
0
    if (g.ContextName[0] != 0)
13871
0
        SeparatorText(g.ContextName);
13872
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
13873
0
    {
13874
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
13875
0
        IM_ASSERT(window != NULL); // Fix static analyzers
13876
0
        if (!IsWindowNavFocusable(window))
13877
0
            continue;
13878
0
        const char* label = window->Name;
13879
0
        if (label == FindRenderedTextEnd(label))
13880
0
            label = GetFallbackWindowNameForWindowingList(window);
13881
0
        Selectable(label, g.NavWindowingTarget == window);
13882
0
    }
13883
0
    End();
13884
0
    PopStyleVar();
13885
0
}
13886
13887
13888
//-----------------------------------------------------------------------------
13889
// [SECTION] DRAG AND DROP
13890
//-----------------------------------------------------------------------------
13891
13892
bool ImGui::IsDragDropActive()
13893
0
{
13894
0
    ImGuiContext& g = *GImGui;
13895
0
    return g.DragDropActive;
13896
0
}
13897
13898
void ImGui::ClearDragDrop()
13899
4
{
13900
4
    ImGuiContext& g = *GImGui;
13901
4
    if (g.DragDropActive)
13902
2
        IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] ClearDragDrop()\n");
13903
4
    g.DragDropActive = false;
13904
4
    g.DragDropPayload.Clear();
13905
4
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
13906
4
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
13907
4
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
13908
4
    g.DragDropAcceptFrameCount = -1;
13909
13910
4
    g.DragDropPayloadBufHeap.clear();
13911
4
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13912
4
}
13913
13914
bool ImGui::BeginTooltipHidden()
13915
0
{
13916
0
    ImGuiContext& g = *GImGui;
13917
0
    bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
13918
0
    SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
13919
0
    return ret;
13920
0
}
13921
13922
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
13923
// If the item has an identifier:
13924
// - This assume/require the item to be activated (typically via ButtonBehavior).
13925
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
13926
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13927
// If the item has no identifier:
13928
// - Currently always assume left mouse button.
13929
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13930
48
{
13931
48
    ImGuiContext& g = *GImGui;
13932
48
    ImGuiWindow* window = g.CurrentWindow;
13933
13934
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13935
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13936
48
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13937
13938
48
    bool source_drag_active = false;
13939
48
    ImGuiID source_id = 0;
13940
48
    ImGuiID source_parent_id = 0;
13941
48
    if ((flags & ImGuiDragDropFlags_SourceExtern) == 0)
13942
48
    {
13943
48
        source_id = g.LastItemData.ID;
13944
48
        if (source_id != 0)
13945
48
        {
13946
            // Common path: items with ID
13947
48
            if (g.ActiveId != source_id)
13948
0
                return false;
13949
48
            if (g.ActiveIdMouseButton != -1)
13950
0
                mouse_button = g.ActiveIdMouseButton;
13951
48
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13952
0
                return false;
13953
48
            g.ActiveIdAllowOverlap = false;
13954
48
        }
13955
0
        else
13956
0
        {
13957
            // Uncommon path: items without ID
13958
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13959
0
                return false;
13960
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
13961
0
                return false;
13962
13963
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
13964
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
13965
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
13966
0
            {
13967
0
                IM_ASSERT(0);
13968
0
                return false;
13969
0
            }
13970
13971
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
13972
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
13973
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
13974
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
13975
            // Rely on keeping other window->LastItemXXX fields intact.
13976
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
13977
0
            KeepAliveID(source_id);
13978
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.InFlags);
13979
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
13980
0
            {
13981
0
                SetActiveID(source_id, window);
13982
0
                FocusWindow(window);
13983
0
            }
13984
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
13985
0
                g.ActiveIdAllowOverlap = is_hovered;
13986
0
        }
13987
48
        if (g.ActiveId != source_id)
13988
0
            return false;
13989
48
        source_parent_id = window->IDStack.back();
13990
48
        source_drag_active = IsMouseDragging(mouse_button);
13991
13992
        // Disable navigation and key inputs while dragging + cancel existing request if any
13993
48
        SetActiveIdUsingAllKeyboardKeys();
13994
48
    }
13995
0
    else
13996
0
    {
13997
        // When ImGuiDragDropFlags_SourceExtern is set:
13998
0
        window = NULL;
13999
0
        source_id = ImHashStr("#SourceExtern");
14000
0
        source_drag_active = true;
14001
0
        mouse_button = g.IO.MouseDown[0] ? 0 : -1;
14002
0
        KeepAliveID(source_id);
14003
0
        SetActiveID(source_id, NULL);
14004
0
    }
14005
14006
48
    IM_ASSERT(g.DragDropWithinTarget == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14007
48
    if (!source_drag_active)
14008
32
        return false;
14009
14010
    // Activate drag and drop
14011
16
    if (!g.DragDropActive)
14012
2
    {
14013
2
        IM_ASSERT(source_id != 0);
14014
2
        ClearDragDrop();
14015
2
        IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] BeginDragDropSource() DragDropActive = true, source_id = 0x%08X%s\n",
14016
2
            source_id, (flags & ImGuiDragDropFlags_SourceExtern) ? " (EXTERN)" : "");
14017
2
        ImGuiPayload& payload = g.DragDropPayload;
14018
2
        payload.SourceId = source_id;
14019
2
        payload.SourceParentId = source_parent_id;
14020
2
        g.DragDropActive = true;
14021
2
        g.DragDropSourceFlags = flags;
14022
2
        g.DragDropMouseButton = mouse_button;
14023
2
        if (payload.SourceId == g.ActiveId)
14024
2
            g.ActiveIdNoClearOnFocusLoss = true;
14025
2
    }
14026
16
    g.DragDropSourceFrameCount = g.FrameCount;
14027
16
    g.DragDropWithinSource = true;
14028
14029
16
    if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
14030
0
    {
14031
        // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
14032
        // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
14033
0
        bool ret;
14034
0
        if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
14035
0
            ret = BeginTooltipHidden();
14036
0
        else
14037
0
            ret = BeginTooltip();
14038
0
        IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
14039
0
        IM_UNUSED(ret);
14040
0
    }
14041
14042
16
    if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
14043
16
        g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
14044
14045
16
    return true;
14046
48
}
14047
14048
void ImGui::EndDragDropSource()
14049
16
{
14050
16
    ImGuiContext& g = *GImGui;
14051
16
    IM_ASSERT(g.DragDropActive);
14052
16
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
14053
14054
16
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
14055
0
        EndTooltip();
14056
14057
    // Discard the drag if have not called SetDragDropPayload()
14058
16
    if (g.DragDropPayload.DataFrameCount == -1)
14059
0
        ClearDragDrop();
14060
16
    g.DragDropWithinSource = false;
14061
16
}
14062
14063
// Use 'cond' to choose to submit payload on drag start or every frame
14064
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
14065
16
{
14066
16
    ImGuiContext& g = *GImGui;
14067
16
    ImGuiPayload& payload = g.DragDropPayload;
14068
16
    if (cond == 0)
14069
16
        cond = ImGuiCond_Always;
14070
14071
16
    IM_ASSERT(type != NULL);
14072
16
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
14073
16
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
14074
16
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
14075
16
    IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
14076
14077
16
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
14078
16
    {
14079
        // Copy payload
14080
16
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
14081
16
        g.DragDropPayloadBufHeap.resize(0);
14082
16
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
14083
0
        {
14084
            // Store in heap
14085
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
14086
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
14087
0
            memcpy(payload.Data, data, data_size);
14088
0
        }
14089
16
        else if (data_size > 0)
14090
16
        {
14091
            // Store locally
14092
16
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
14093
16
            payload.Data = g.DragDropPayloadBufLocal;
14094
16
            memcpy(payload.Data, data, data_size);
14095
16
        }
14096
0
        else
14097
0
        {
14098
0
            payload.Data = NULL;
14099
0
        }
14100
16
        payload.DataSize = (int)data_size;
14101
16
    }
14102
16
    payload.DataFrameCount = g.FrameCount;
14103
14104
    // Return whether the payload has been accepted
14105
16
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
14106
16
}
14107
14108
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
14109
22
{
14110
22
    ImGuiContext& g = *GImGui;
14111
22
    if (!g.DragDropActive)
14112
0
        return false;
14113
14114
22
    ImGuiWindow* window = g.CurrentWindow;
14115
22
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
14116
22
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
14117
21
        return false;
14118
1
    IM_ASSERT(id != 0);
14119
1
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
14120
0
        return false;
14121
1
    if (window->SkipItems)
14122
0
        return false;
14123
14124
1
    IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14125
1
    g.DragDropTargetRect = bb;
14126
1
    g.DragDropTargetClipRect = window->ClipRect; // May want to be overriden by user depending on use case?
14127
1
    g.DragDropTargetId = id;
14128
1
    g.DragDropWithinTarget = true;
14129
1
    return true;
14130
1
}
14131
14132
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
14133
// 1) we use LastItemData's ImGuiItemStatusFlags_HoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
14134
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
14135
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
14136
bool ImGui::BeginDragDropTarget()
14137
0
{
14138
0
    ImGuiContext& g = *GImGui;
14139
0
    if (!g.DragDropActive)
14140
0
        return false;
14141
14142
0
    ImGuiWindow* window = g.CurrentWindow;
14143
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
14144
0
        return false;
14145
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
14146
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
14147
0
        return false;
14148
14149
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
14150
0
    ImGuiID id = g.LastItemData.ID;
14151
0
    if (id == 0)
14152
0
    {
14153
0
        id = window->GetIDFromRectangle(display_rect);
14154
0
        KeepAliveID(id);
14155
0
    }
14156
0
    if (g.DragDropPayload.SourceId == id)
14157
0
        return false;
14158
14159
0
    IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14160
0
    g.DragDropTargetRect = display_rect;
14161
0
    g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
14162
0
    g.DragDropTargetId = id;
14163
0
    g.DragDropWithinTarget = true;
14164
0
    return true;
14165
0
}
14166
14167
bool ImGui::IsDragDropPayloadBeingAccepted()
14168
4
{
14169
4
    ImGuiContext& g = *GImGui;
14170
4
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
14171
4
}
14172
14173
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
14174
1
{
14175
1
    ImGuiContext& g = *GImGui;
14176
1
    ImGuiPayload& payload = g.DragDropPayload;
14177
1
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
14178
1
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
14179
1
    if (type != NULL && !payload.IsDataType(type))
14180
0
        return NULL;
14181
14182
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
14183
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
14184
1
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
14185
1
    ImRect r = g.DragDropTargetRect;
14186
1
    float r_surface = r.GetWidth() * r.GetHeight();
14187
1
    if (r_surface > g.DragDropAcceptIdCurrRectSurface)
14188
0
        return NULL;
14189
14190
1
    g.DragDropAcceptFlags = flags;
14191
1
    g.DragDropAcceptIdCurr = g.DragDropTargetId;
14192
1
    g.DragDropAcceptIdCurrRectSurface = r_surface;
14193
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
14194
14195
    // Render default drop visuals
14196
1
    payload.Preview = was_accepted_previously;
14197
1
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
14198
1
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
14199
0
        RenderDragDropTargetRect(r, g.DragDropTargetClipRect);
14200
14201
1
    g.DragDropAcceptFrameCount = g.FrameCount;
14202
1
    if ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) && g.DragDropMouseButton == -1)
14203
0
        payload.Delivery = was_accepted_previously && (g.DragDropSourceFrameCount < g.FrameCount);
14204
1
    else
14205
1
        payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
14206
1
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
14207
0
        return NULL;
14208
14209
1
    if (payload.Delivery)
14210
0
        IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] AcceptDragDropPayload(): 0x%08X: payload delivery\n", g.DragDropTargetId);
14211
1
    return &payload;
14212
1
}
14213
14214
// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
14215
void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect)
14216
0
{
14217
0
    ImGuiContext& g = *GImGui;
14218
0
    ImGuiWindow* window = g.CurrentWindow;
14219
0
    ImRect bb_display = bb;
14220
0
    bb_display.ClipWith(item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
14221
0
    bb_display.Expand(3.5f);
14222
0
    bool push_clip_rect = !window->ClipRect.Contains(bb_display);
14223
0
    if (push_clip_rect)
14224
0
        window->DrawList->PushClipRectFullScreen();
14225
0
    window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
14226
0
    if (push_clip_rect)
14227
0
        window->DrawList->PopClipRect();
14228
0
}
14229
14230
const ImGuiPayload* ImGui::GetDragDropPayload()
14231
0
{
14232
0
    ImGuiContext& g = *GImGui;
14233
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
14234
0
}
14235
14236
void ImGui::EndDragDropTarget()
14237
1
{
14238
1
    ImGuiContext& g = *GImGui;
14239
1
    IM_ASSERT(g.DragDropActive);
14240
1
    IM_ASSERT(g.DragDropWithinTarget);
14241
1
    g.DragDropWithinTarget = false;
14242
14243
    // Clear drag and drop state payload right after delivery
14244
1
    if (g.DragDropPayload.Delivery)
14245
0
        ClearDragDrop();
14246
1
}
14247
14248
//-----------------------------------------------------------------------------
14249
// [SECTION] LOGGING/CAPTURING
14250
//-----------------------------------------------------------------------------
14251
// All text output from the interface can be captured into tty/file/clipboard.
14252
// By default, tree nodes are automatically opened during logging.
14253
//-----------------------------------------------------------------------------
14254
14255
// Pass text data straight to log (without being displayed)
14256
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
14257
0
{
14258
0
    if (g.LogFile)
14259
0
    {
14260
0
        g.LogBuffer.Buf.resize(0);
14261
0
        g.LogBuffer.appendfv(fmt, args);
14262
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
14263
0
    }
14264
0
    else
14265
0
    {
14266
0
        g.LogBuffer.appendfv(fmt, args);
14267
0
    }
14268
0
}
14269
14270
void ImGui::LogText(const char* fmt, ...)
14271
0
{
14272
0
    ImGuiContext& g = *GImGui;
14273
0
    if (!g.LogEnabled)
14274
0
        return;
14275
14276
0
    va_list args;
14277
0
    va_start(args, fmt);
14278
0
    LogTextV(g, fmt, args);
14279
0
    va_end(args);
14280
0
}
14281
14282
void ImGui::LogTextV(const char* fmt, va_list args)
14283
0
{
14284
0
    ImGuiContext& g = *GImGui;
14285
0
    if (!g.LogEnabled)
14286
0
        return;
14287
14288
0
    LogTextV(g, fmt, args);
14289
0
}
14290
14291
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
14292
// We split text into individual lines to add current tree level padding
14293
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
14294
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
14295
0
{
14296
0
    ImGuiContext& g = *GImGui;
14297
0
    ImGuiWindow* window = g.CurrentWindow;
14298
14299
0
    const char* prefix = g.LogNextPrefix;
14300
0
    const char* suffix = g.LogNextSuffix;
14301
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
14302
14303
0
    if (!text_end)
14304
0
        text_end = FindRenderedTextEnd(text, text_end);
14305
14306
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
14307
0
    if (ref_pos)
14308
0
        g.LogLinePosY = ref_pos->y;
14309
0
    if (log_new_line)
14310
0
    {
14311
0
        LogText(IM_NEWLINE);
14312
0
        g.LogLineFirstItem = true;
14313
0
    }
14314
14315
0
    if (prefix)
14316
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
14317
14318
    // Re-adjust padding if we have popped out of our starting depth
14319
0
    if (g.LogDepthRef > window->DC.TreeDepth)
14320
0
        g.LogDepthRef = window->DC.TreeDepth;
14321
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
14322
14323
0
    const char* text_remaining = text;
14324
0
    for (;;)
14325
0
    {
14326
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
14327
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
14328
0
        const char* line_start = text_remaining;
14329
0
        const char* line_end = ImStreolRange(line_start, text_end);
14330
0
        const bool is_last_line = (line_end == text_end);
14331
0
        if (line_start != line_end || !is_last_line)
14332
0
        {
14333
0
            const int line_length = (int)(line_end - line_start);
14334
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
14335
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
14336
0
            g.LogLineFirstItem = false;
14337
0
            if (*line_end == '\n')
14338
0
            {
14339
0
                LogText(IM_NEWLINE);
14340
0
                g.LogLineFirstItem = true;
14341
0
            }
14342
0
        }
14343
0
        if (is_last_line)
14344
0
            break;
14345
0
        text_remaining = line_end + 1;
14346
0
    }
14347
14348
0
    if (suffix)
14349
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
14350
0
}
14351
14352
// Start logging/capturing text output
14353
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
14354
0
{
14355
0
    ImGuiContext& g = *GImGui;
14356
0
    ImGuiWindow* window = g.CurrentWindow;
14357
0
    IM_ASSERT(g.LogEnabled == false);
14358
0
    IM_ASSERT(g.LogFile == NULL);
14359
0
    IM_ASSERT(g.LogBuffer.empty());
14360
0
    g.LogEnabled = g.ItemUnclipByLog = true;
14361
0
    g.LogType = type;
14362
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
14363
0
    g.LogDepthRef = window->DC.TreeDepth;
14364
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
14365
0
    g.LogLinePosY = FLT_MAX;
14366
0
    g.LogLineFirstItem = true;
14367
0
}
14368
14369
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
14370
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
14371
0
{
14372
0
    ImGuiContext& g = *GImGui;
14373
0
    g.LogNextPrefix = prefix;
14374
0
    g.LogNextSuffix = suffix;
14375
0
}
14376
14377
void ImGui::LogToTTY(int auto_open_depth)
14378
0
{
14379
0
    ImGuiContext& g = *GImGui;
14380
0
    if (g.LogEnabled)
14381
0
        return;
14382
0
    IM_UNUSED(auto_open_depth);
14383
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14384
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
14385
0
    g.LogFile = stdout;
14386
0
#endif
14387
0
}
14388
14389
// Start logging/capturing text output to given file
14390
void ImGui::LogToFile(int auto_open_depth, const char* filename)
14391
0
{
14392
0
    ImGuiContext& g = *GImGui;
14393
0
    if (g.LogEnabled)
14394
0
        return;
14395
14396
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
14397
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
14398
    // By opening the file in binary mode "ab" we have consistent output everywhere.
14399
0
    if (!filename)
14400
0
        filename = g.IO.LogFilename;
14401
0
    if (!filename || !filename[0])
14402
0
        return;
14403
0
    ImFileHandle f = ImFileOpen(filename, "ab");
14404
0
    if (!f)
14405
0
    {
14406
0
        IM_ASSERT(0);
14407
0
        return;
14408
0
    }
14409
14410
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
14411
0
    g.LogFile = f;
14412
0
}
14413
14414
// Start logging/capturing text output to clipboard
14415
void ImGui::LogToClipboard(int auto_open_depth)
14416
0
{
14417
0
    ImGuiContext& g = *GImGui;
14418
0
    if (g.LogEnabled)
14419
0
        return;
14420
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
14421
0
}
14422
14423
void ImGui::LogToBuffer(int auto_open_depth)
14424
0
{
14425
0
    ImGuiContext& g = *GImGui;
14426
0
    if (g.LogEnabled)
14427
0
        return;
14428
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
14429
0
}
14430
14431
void ImGui::LogFinish()
14432
158k
{
14433
158k
    ImGuiContext& g = *GImGui;
14434
158k
    if (!g.LogEnabled)
14435
158k
        return;
14436
14437
0
    LogText(IM_NEWLINE);
14438
0
    switch (g.LogType)
14439
0
    {
14440
0
    case ImGuiLogType_TTY:
14441
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14442
0
        fflush(g.LogFile);
14443
0
#endif
14444
0
        break;
14445
0
    case ImGuiLogType_File:
14446
0
        ImFileClose(g.LogFile);
14447
0
        break;
14448
0
    case ImGuiLogType_Buffer:
14449
0
        break;
14450
0
    case ImGuiLogType_Clipboard:
14451
0
        if (!g.LogBuffer.empty())
14452
0
            SetClipboardText(g.LogBuffer.begin());
14453
0
        break;
14454
0
    case ImGuiLogType_None:
14455
0
        IM_ASSERT(0);
14456
0
        break;
14457
0
    }
14458
14459
0
    g.LogEnabled = g.ItemUnclipByLog = false;
14460
0
    g.LogType = ImGuiLogType_None;
14461
0
    g.LogFile = NULL;
14462
0
    g.LogBuffer.clear();
14463
0
}
14464
14465
// Helper to display logging buttons
14466
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
14467
void ImGui::LogButtons()
14468
0
{
14469
0
    ImGuiContext& g = *GImGui;
14470
14471
0
    PushID("LogButtons");
14472
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14473
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
14474
#else
14475
    const bool log_to_tty = false;
14476
#endif
14477
0
    const bool log_to_file = Button("Log To File"); SameLine();
14478
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
14479
0
    PushTabStop(false);
14480
0
    SetNextItemWidth(80.0f);
14481
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
14482
0
    PopTabStop();
14483
0
    PopID();
14484
14485
    // Start logging at the end of the function so that the buttons don't appear in the log
14486
0
    if (log_to_tty)
14487
0
        LogToTTY();
14488
0
    if (log_to_file)
14489
0
        LogToFile();
14490
0
    if (log_to_clipboard)
14491
0
        LogToClipboard();
14492
0
}
14493
14494
14495
//-----------------------------------------------------------------------------
14496
// [SECTION] SETTINGS
14497
//-----------------------------------------------------------------------------
14498
// - UpdateSettings() [Internal]
14499
// - MarkIniSettingsDirty() [Internal]
14500
// - FindSettingsHandler() [Internal]
14501
// - ClearIniSettings() [Internal]
14502
// - LoadIniSettingsFromDisk()
14503
// - LoadIniSettingsFromMemory()
14504
// - SaveIniSettingsToDisk()
14505
// - SaveIniSettingsToMemory()
14506
//-----------------------------------------------------------------------------
14507
// - CreateNewWindowSettings() [Internal]
14508
// - FindWindowSettingsByID() [Internal]
14509
// - FindWindowSettingsByWindow() [Internal]
14510
// - ClearWindowSettings() [Internal]
14511
// - WindowSettingsHandler_***() [Internal]
14512
//-----------------------------------------------------------------------------
14513
14514
// Called by NewFrame()
14515
void ImGui::UpdateSettings()
14516
79.1k
{
14517
    // Load settings on first frame (if not explicitly loaded manually before)
14518
79.1k
    ImGuiContext& g = *GImGui;
14519
79.1k
    if (!g.SettingsLoaded)
14520
1
    {
14521
1
        IM_ASSERT(g.SettingsWindows.empty());
14522
1
        if (g.IO.IniFilename)
14523
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
14524
1
        g.SettingsLoaded = true;
14525
1
    }
14526
14527
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
14528
79.1k
    if (g.SettingsDirtyTimer > 0.0f)
14529
900
    {
14530
900
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
14531
900
        if (g.SettingsDirtyTimer <= 0.0f)
14532
3
        {
14533
3
            if (g.IO.IniFilename != NULL)
14534
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
14535
3
            else
14536
3
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
14537
3
            g.SettingsDirtyTimer = 0.0f;
14538
3
        }
14539
900
    }
14540
79.1k
}
14541
14542
void ImGui::MarkIniSettingsDirty()
14543
0
{
14544
0
    ImGuiContext& g = *GImGui;
14545
0
    if (g.SettingsDirtyTimer <= 0.0f)
14546
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
14547
0
}
14548
14549
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
14550
11.3k
{
14551
11.3k
    ImGuiContext& g = *GImGui;
14552
11.3k
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
14553
12
        if (g.SettingsDirtyTimer <= 0.0f)
14554
3
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
14555
11.3k
}
14556
14557
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
14558
2
{
14559
2
    ImGuiContext& g = *GImGui;
14560
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
14561
2
    g.SettingsHandlers.push_back(*handler);
14562
2
}
14563
14564
void ImGui::RemoveSettingsHandler(const char* type_name)
14565
0
{
14566
0
    ImGuiContext& g = *GImGui;
14567
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
14568
0
        g.SettingsHandlers.erase(handler);
14569
0
}
14570
14571
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
14572
2
{
14573
2
    ImGuiContext& g = *GImGui;
14574
2
    const ImGuiID type_hash = ImHashStr(type_name);
14575
2
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14576
1
        if (handler.TypeHash == type_hash)
14577
0
            return &handler;
14578
2
    return NULL;
14579
2
}
14580
14581
// Clear all settings (windows, tables, docking etc.)
14582
void ImGui::ClearIniSettings()
14583
0
{
14584
0
    ImGuiContext& g = *GImGui;
14585
0
    g.SettingsIniData.clear();
14586
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14587
0
        if (handler.ClearAllFn != NULL)
14588
0
            handler.ClearAllFn(&g, &handler);
14589
0
}
14590
14591
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
14592
0
{
14593
0
    size_t file_data_size = 0;
14594
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
14595
0
    if (!file_data)
14596
0
        return;
14597
0
    if (file_data_size > 0)
14598
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
14599
0
    IM_FREE(file_data);
14600
0
}
14601
14602
// Zero-tolerance, no error reporting, cheap .ini parsing
14603
// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
14604
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
14605
0
{
14606
0
    ImGuiContext& g = *GImGui;
14607
0
    IM_ASSERT(g.Initialized);
14608
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
14609
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
14610
14611
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
14612
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
14613
0
    if (ini_size == 0)
14614
0
        ini_size = strlen(ini_data);
14615
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
14616
0
    char* const buf = g.SettingsIniData.Buf.Data;
14617
0
    char* const buf_end = buf + ini_size;
14618
0
    memcpy(buf, ini_data, ini_size);
14619
0
    buf_end[0] = 0;
14620
14621
    // Call pre-read handlers
14622
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
14623
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14624
0
        if (handler.ReadInitFn != NULL)
14625
0
            handler.ReadInitFn(&g, &handler);
14626
14627
0
    void* entry_data = NULL;
14628
0
    ImGuiSettingsHandler* entry_handler = NULL;
14629
14630
0
    char* line_end = NULL;
14631
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
14632
0
    {
14633
        // Skip new lines markers, then find end of the line
14634
0
        while (*line == '\n' || *line == '\r')
14635
0
            line++;
14636
0
        line_end = line;
14637
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
14638
0
            line_end++;
14639
0
        line_end[0] = 0;
14640
0
        if (line[0] == ';')
14641
0
            continue;
14642
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
14643
0
        {
14644
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
14645
0
            line_end[-1] = 0;
14646
0
            const char* name_end = line_end - 1;
14647
0
            const char* type_start = line + 1;
14648
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
14649
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
14650
0
            if (!type_end || !name_start)
14651
0
                continue;
14652
0
            *type_end = 0; // Overwrite first ']'
14653
0
            name_start++;  // Skip second '['
14654
0
            entry_handler = FindSettingsHandler(type_start);
14655
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
14656
0
        }
14657
0
        else if (entry_handler != NULL && entry_data != NULL)
14658
0
        {
14659
            // Let type handler parse the line
14660
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
14661
0
        }
14662
0
    }
14663
0
    g.SettingsLoaded = true;
14664
14665
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
14666
0
    memcpy(buf, ini_data, ini_size);
14667
14668
    // Call post-read handlers
14669
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14670
0
        if (handler.ApplyAllFn != NULL)
14671
0
            handler.ApplyAllFn(&g, &handler);
14672
0
}
14673
14674
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
14675
0
{
14676
0
    ImGuiContext& g = *GImGui;
14677
0
    g.SettingsDirtyTimer = 0.0f;
14678
0
    if (!ini_filename)
14679
0
        return;
14680
14681
0
    size_t ini_data_size = 0;
14682
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
14683
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
14684
0
    if (!f)
14685
0
        return;
14686
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
14687
0
    ImFileClose(f);
14688
0
}
14689
14690
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
14691
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
14692
0
{
14693
0
    ImGuiContext& g = *GImGui;
14694
0
    g.SettingsDirtyTimer = 0.0f;
14695
0
    g.SettingsIniData.Buf.resize(0);
14696
0
    g.SettingsIniData.Buf.push_back(0);
14697
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14698
0
        handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
14699
0
    if (out_size)
14700
0
        *out_size = (size_t)g.SettingsIniData.size();
14701
0
    return g.SettingsIniData.c_str();
14702
0
}
14703
14704
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
14705
0
{
14706
0
    ImGuiContext& g = *GImGui;
14707
14708
0
    if (g.IO.ConfigDebugIniSettings == false)
14709
0
    {
14710
        // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
14711
        // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
14712
0
        if (const char* p = strstr(name, "###"))
14713
0
            name = p;
14714
0
    }
14715
0
    const size_t name_len = strlen(name);
14716
14717
    // Allocate chunk
14718
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
14719
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
14720
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
14721
0
    settings->ID = ImHashStr(name, name_len);
14722
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
14723
14724
0
    return settings;
14725
0
}
14726
14727
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
14728
// This is called once per window .ini entry + once per newly instantiated window.
14729
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
14730
2
{
14731
2
    ImGuiContext& g = *GImGui;
14732
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14733
0
        if (settings->ID == id && !settings->WantDelete)
14734
0
            return settings;
14735
2
    return NULL;
14736
2
}
14737
14738
// This is faster if you are holding on a Window already as we don't need to perform a search.
14739
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
14740
2
{
14741
2
    ImGuiContext& g = *GImGui;
14742
2
    if (window->SettingsOffset != -1)
14743
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
14744
2
    return FindWindowSettingsByID(window->ID);
14745
2
}
14746
14747
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
14748
void ImGui::ClearWindowSettings(const char* name)
14749
0
{
14750
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
14751
0
    ImGuiContext& g = *GImGui;
14752
0
    ImGuiWindow* window = FindWindowByName(name);
14753
0
    if (window != NULL)
14754
0
    {
14755
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
14756
0
        InitOrLoadWindowSettings(window, NULL);
14757
0
        if (window->DockId != 0)
14758
0
            DockContextProcessUndockWindow(&g, window, true);
14759
0
    }
14760
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
14761
0
        settings->WantDelete = true;
14762
0
}
14763
14764
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14765
0
{
14766
0
    ImGuiContext& g = *ctx;
14767
0
    for (ImGuiWindow* window : g.Windows)
14768
0
        window->SettingsOffset = -1;
14769
0
    g.SettingsWindows.clear();
14770
0
}
14771
14772
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
14773
0
{
14774
0
    ImGuiID id = ImHashStr(name);
14775
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
14776
0
    if (settings)
14777
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
14778
0
    else
14779
0
        settings = ImGui::CreateNewWindowSettings(name);
14780
0
    settings->ID = id;
14781
0
    settings->WantApply = true;
14782
0
    return (void*)settings;
14783
0
}
14784
14785
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
14786
0
{
14787
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
14788
0
    int x, y;
14789
0
    int i;
14790
0
    ImU32 u1;
14791
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
14792
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
14793
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
14794
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
14795
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
14796
0
    else if (sscanf(line, "IsChild=%d", &i) == 1)           { settings->IsChild = (i != 0); }
14797
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
14798
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
14799
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
14800
0
}
14801
14802
// Apply to existing windows (if any)
14803
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14804
0
{
14805
0
    ImGuiContext& g = *ctx;
14806
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14807
0
        if (settings->WantApply)
14808
0
        {
14809
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
14810
0
                ApplyWindowSettings(window, settings);
14811
0
            settings->WantApply = false;
14812
0
        }
14813
0
}
14814
14815
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
14816
0
{
14817
    // Gather data from windows that were active during this session
14818
    // (if a window wasn't opened in this session we preserve its settings)
14819
0
    ImGuiContext& g = *ctx;
14820
0
    for (ImGuiWindow* window : g.Windows)
14821
0
    {
14822
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
14823
0
            continue;
14824
14825
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
14826
0
        if (!settings)
14827
0
        {
14828
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
14829
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
14830
0
        }
14831
0
        IM_ASSERT(settings->ID == window->ID);
14832
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
14833
0
        settings->Size = ImVec2ih(window->SizeFull);
14834
0
        settings->ViewportId = window->ViewportId;
14835
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
14836
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
14837
0
        settings->DockId = window->DockId;
14838
0
        settings->ClassId = window->WindowClass.ClassId;
14839
0
        settings->DockOrder = window->DockOrder;
14840
0
        settings->Collapsed = window->Collapsed;
14841
0
        settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set.
14842
0
        settings->WantDelete = false;
14843
0
    }
14844
14845
    // Write to text buffer
14846
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
14847
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14848
0
    {
14849
0
        if (settings->WantDelete)
14850
0
            continue;
14851
0
        const char* settings_name = settings->GetName();
14852
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
14853
0
        if (settings->IsChild)
14854
0
        {
14855
0
            buf->appendf("IsChild=1\n");
14856
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14857
0
        }
14858
0
        else
14859
0
        {
14860
0
            if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14861
0
            {
14862
0
                buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
14863
0
                buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
14864
0
            }
14865
0
            if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14866
0
                buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
14867
0
            if (settings->Size.x != 0 || settings->Size.y != 0)
14868
0
                buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14869
0
            buf->appendf("Collapsed=%d\n", settings->Collapsed);
14870
0
            if (settings->DockId != 0)
14871
0
            {
14872
                //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
14873
0
                if (settings->DockOrder == -1)
14874
0
                    buf->appendf("DockId=0x%08X\n", settings->DockId);
14875
0
                else
14876
0
                    buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
14877
0
                if (settings->ClassId != 0)
14878
0
                    buf->appendf("ClassId=0x%08X\n", settings->ClassId);
14879
0
            }
14880
0
        }
14881
0
        buf->append("\n");
14882
0
    }
14883
0
}
14884
14885
14886
//-----------------------------------------------------------------------------
14887
// [SECTION] LOCALIZATION
14888
//-----------------------------------------------------------------------------
14889
14890
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
14891
1
{
14892
1
    ImGuiContext& g = *GImGui;
14893
13
    for (int n = 0; n < count; n++)
14894
12
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
14895
1
}
14896
14897
14898
//-----------------------------------------------------------------------------
14899
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
14900
//-----------------------------------------------------------------------------
14901
// - GetMainViewport()
14902
// - FindViewportByID()
14903
// - FindViewportByPlatformHandle()
14904
// - SetCurrentViewport() [Internal]
14905
// - SetWindowViewport() [Internal]
14906
// - GetWindowAlwaysWantOwnViewport() [Internal]
14907
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
14908
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
14909
// - TranslateWindowsInViewport() [Internal]
14910
// - ScaleWindowsInViewport() [Internal]
14911
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
14912
// - UpdateViewportsNewFrame() [Internal]
14913
// - UpdateViewportsEndFrame() [Internal]
14914
// - AddUpdateViewport() [Internal]
14915
// - WindowSelectViewport() [Internal]
14916
// - WindowSyncOwnedViewport() [Internal]
14917
// - UpdatePlatformWindows()
14918
// - RenderPlatformWindowsDefault()
14919
// - FindPlatformMonitorForPos() [Internal]
14920
// - FindPlatformMonitorForRect() [Internal]
14921
// - UpdateViewportPlatformMonitor() [Internal]
14922
// - DestroyPlatformWindow() [Internal]
14923
// - DestroyPlatformWindows()
14924
//-----------------------------------------------------------------------------
14925
14926
ImGuiViewport* ImGui::GetMainViewport()
14927
327k
{
14928
327k
    ImGuiContext& g = *GImGui;
14929
327k
    return g.Viewports[0];
14930
327k
}
14931
14932
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
14933
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
14934
79.1k
{
14935
79.1k
    ImGuiContext& g = *GImGui;
14936
79.1k
    for (ImGuiViewportP* viewport : g.Viewports)
14937
79.1k
        if (viewport->ID == id)
14938
79.1k
            return viewport;
14939
0
    return NULL;
14940
79.1k
}
14941
14942
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
14943
0
{
14944
0
    ImGuiContext& g = *GImGui;
14945
0
    for (ImGuiViewportP* viewport : g.Viewports)
14946
0
        if (viewport->PlatformHandle == platform_handle)
14947
0
            return viewport;
14948
0
    return NULL;
14949
0
}
14950
14951
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
14952
339k
{
14953
339k
    ImGuiContext& g = *GImGui;
14954
339k
    (void)current_window;
14955
14956
339k
    if (viewport)
14957
260k
        viewport->LastFrameActive = g.FrameCount;
14958
339k
    if (g.CurrentViewport == viewport)
14959
181k
        return;
14960
158k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
14961
158k
    g.CurrentViewport = viewport;
14962
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
14963
14964
    // Notify platform layer of viewport changes
14965
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
14966
158k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
14967
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
14968
158k
}
14969
14970
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14971
169k
{
14972
    // Abandon viewport
14973
169k
    if (window->ViewportOwned && window->Viewport->Window == window)
14974
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
14975
14976
169k
    window->Viewport = viewport;
14977
169k
    window->ViewportId = viewport->ID;
14978
169k
    window->ViewportOwned = (viewport->Window == window);
14979
169k
}
14980
14981
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
14982
0
{
14983
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
14984
0
    ImGuiContext& g = *GImGui;
14985
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
14986
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
14987
0
            if (!window->DockIsActive)
14988
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
14989
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
14990
0
                        return true;
14991
0
    return false;
14992
0
}
14993
14994
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14995
0
{
14996
0
    ImGuiContext& g = *GImGui;
14997
0
    if (window->Viewport == viewport)
14998
0
        return false;
14999
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
15000
0
        return false;
15001
0
    if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
15002
0
        return false;
15003
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
15004
0
        return false;
15005
0
    if (GetWindowAlwaysWantOwnViewport(window))
15006
0
        return false;
15007
15008
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
15009
0
    for (ImGuiWindow* window_behind : g.Windows)
15010
0
    {
15011
0
        if (window_behind == window)
15012
0
            break;
15013
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
15014
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
15015
0
                return false;
15016
0
    }
15017
15018
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
15019
0
    ImGuiViewportP* old_viewport = window->Viewport;
15020
0
    if (window->ViewportOwned)
15021
0
        for (int n = 0; n < g.Windows.Size; n++)
15022
0
            if (g.Windows[n]->Viewport == old_viewport)
15023
0
                SetWindowViewport(g.Windows[n], viewport);
15024
0
    SetWindowViewport(window, viewport);
15025
0
    BringWindowToDisplayFront(window);
15026
15027
0
    return true;
15028
0
}
15029
15030
// FIXME: handle 0 to N host viewports
15031
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
15032
0
{
15033
0
    ImGuiContext& g = *GImGui;
15034
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
15035
0
}
15036
15037
// Translate Dear ImGui windows when a Host Viewport has been moved
15038
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
15039
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
15040
0
{
15041
0
    ImGuiContext& g = *GImGui;
15042
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
15043
15044
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
15045
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
15046
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
15047
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
15048
    // and so the window will appear to teleport when releasing the mouse.
15049
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
15050
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
15051
0
    ImVec2 delta_pos = new_pos - old_pos;
15052
0
    for (ImGuiWindow* window : g.Windows) // FIXME-OPT
15053
0
        if (translate_all_windows || (window->Viewport == viewport && test_still_fit_rect.Contains(window->Rect())))
15054
0
            TranslateWindow(window, delta_pos);
15055
0
}
15056
15057
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
15058
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
15059
0
{
15060
0
    ImGuiContext& g = *GImGui;
15061
0
    if (viewport->Window)
15062
0
    {
15063
0
        ScaleWindow(viewport->Window, scale);
15064
0
    }
15065
0
    else
15066
0
    {
15067
0
        for (ImGuiWindow* window : g.Windows)
15068
0
            if (window->Viewport == viewport)
15069
0
                ScaleWindow(window, scale);
15070
0
    }
15071
0
}
15072
15073
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
15074
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
15075
// B) It requires Platform_GetWindowFocus to be implemented by backend.
15076
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
15077
0
{
15078
0
    ImGuiContext& g = *GImGui;
15079
0
    ImGuiViewportP* best_candidate = NULL;
15080
0
    for (ImGuiViewportP* viewport : g.Viewports)
15081
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
15082
0
            if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
15083
0
                best_candidate = viewport;
15084
0
    return best_candidate;
15085
0
}
15086
15087
// Update viewports and monitor infos
15088
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
15089
static void ImGui::UpdateViewportsNewFrame()
15090
79.1k
{
15091
79.1k
    ImGuiContext& g = *GImGui;
15092
79.1k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
15093
15094
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
15095
    // Update Focused status
15096
79.1k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
15097
79.1k
    if (viewports_enabled)
15098
0
    {
15099
0
        ImGuiViewportP* focused_viewport = NULL;
15100
0
        for (ImGuiViewportP* viewport : g.Viewports)
15101
0
        {
15102
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
15103
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
15104
0
            {
15105
0
                bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
15106
0
                if (is_minimized)
15107
0
                    viewport->Flags |= ImGuiViewportFlags_IsMinimized;
15108
0
                else
15109
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
15110
0
            }
15111
15112
            // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
15113
            // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
15114
0
            if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
15115
0
            {
15116
0
                bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
15117
0
                if (is_focused)
15118
0
                    viewport->Flags |= ImGuiViewportFlags_IsFocused;
15119
0
                else
15120
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
15121
0
                if (is_focused)
15122
0
                    focused_viewport = viewport;
15123
0
            }
15124
0
        }
15125
15126
        // Focused viewport has changed?
15127
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
15128
0
        {
15129
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
15130
0
            const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
15131
0
            const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
15132
15133
            // Store a tag so we can infer z-order easily from all our windows
15134
            // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
15135
            // will keep the front most stamp instead of losing it back to their parent viewport.
15136
0
            if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15137
0
                focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15138
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
15139
15140
            // Focus associated dear imgui window
15141
            // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
15142
            // - if focus didn't happen because we destroyed another window (#6462)
15143
            // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
15144
0
            const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
15145
0
            if (apply_imgui_focus_on_focused_viewport)
15146
0
            {
15147
0
                focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
15148
0
                ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
15149
0
                if (focused_viewport->Window != NULL)
15150
0
                    FocusWindow(focused_viewport->Window, focus_request_flags);
15151
0
                else if (focused_viewport->LastFocusedHadNavWindow)
15152
0
                    FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
15153
0
                else
15154
0
                    FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
15155
0
            }
15156
0
        }
15157
0
        if (focused_viewport)
15158
0
            focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
15159
0
    }
15160
15161
    // Create/update main viewport with current platform position.
15162
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
15163
79.1k
    ImGuiViewportP* main_viewport = g.Viewports[0];
15164
79.1k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
15165
79.1k
    IM_ASSERT(main_viewport->Window == NULL);
15166
79.1k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
15167
79.1k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
15168
79.1k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
15169
0
    {
15170
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
15171
0
        main_viewport_size = main_viewport->Size;
15172
0
    }
15173
79.1k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
15174
15175
79.1k
    g.CurrentDpiScale = 0.0f;
15176
79.1k
    g.CurrentViewport = NULL;
15177
79.1k
    g.MouseViewport = NULL;
15178
158k
    for (int n = 0; n < g.Viewports.Size; n++)
15179
79.1k
    {
15180
79.1k
        ImGuiViewportP* viewport = g.Viewports[n];
15181
79.1k
        viewport->Idx = n;
15182
15183
        // Erase unused viewports
15184
79.1k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
15185
0
        {
15186
0
            DestroyViewport(viewport);
15187
0
            n--;
15188
0
            continue;
15189
0
        }
15190
15191
79.1k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
15192
79.1k
        if (viewports_enabled)
15193
0
        {
15194
            // Update Position and Size (from Platform Window to ImGui) if requested.
15195
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
15196
0
            if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
15197
0
            {
15198
                // Viewport->WorkPos and WorkSize will be updated below
15199
0
                if (viewport->PlatformRequestMove)
15200
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
15201
0
                if (viewport->PlatformRequestResize)
15202
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
15203
0
            }
15204
0
        }
15205
15206
        // Update/copy monitor info
15207
79.1k
        UpdateViewportPlatformMonitor(viewport);
15208
15209
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
15210
79.1k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
15211
79.1k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
15212
79.1k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
15213
79.1k
        viewport->UpdateWorkRect();
15214
15215
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
15216
79.1k
        viewport->Alpha = 1.0f;
15217
15218
        // Translate Dear ImGui windows when a Host Viewport has been moved
15219
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
15220
79.1k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
15221
79.1k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
15222
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
15223
15224
        // Update DPI scale
15225
79.1k
        float new_dpi_scale;
15226
79.1k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
15227
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
15228
79.1k
        else if (viewport->PlatformMonitor != -1)
15229
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
15230
79.1k
        else
15231
79.1k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
15232
79.1k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
15233
0
        {
15234
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
15235
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
15236
0
                ScaleWindowsInViewport(viewport, scale_factor);
15237
            //if (viewport == GetMainViewport())
15238
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
15239
15240
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
15241
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
15242
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
15243
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
15244
            //    g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
15245
0
        }
15246
79.1k
        viewport->DpiScale = new_dpi_scale;
15247
79.1k
    }
15248
15249
    // Update fallback monitor
15250
79.1k
    g.PlatformMonitorsFullWorkRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
15251
79.1k
    if (g.PlatformIO.Monitors.Size == 0)
15252
79.1k
    {
15253
79.1k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
15254
79.1k
        monitor->MainPos = main_viewport->Pos;
15255
79.1k
        monitor->MainSize = main_viewport->Size;
15256
79.1k
        monitor->WorkPos = main_viewport->WorkPos;
15257
79.1k
        monitor->WorkSize = main_viewport->WorkSize;
15258
79.1k
        monitor->DpiScale = main_viewport->DpiScale;
15259
79.1k
        g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos);
15260
79.1k
        g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos + monitor->WorkSize);
15261
79.1k
    }
15262
79.1k
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
15263
0
    {
15264
0
        g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos);
15265
0
        g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos + monitor.WorkSize);
15266
0
    }
15267
15268
79.1k
    if (!viewports_enabled)
15269
79.1k
    {
15270
79.1k
        g.MouseViewport = main_viewport;
15271
79.1k
        return;
15272
79.1k
    }
15273
15274
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
15275
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
15276
0
    ImGuiViewportP* viewport_hovered = NULL;
15277
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
15278
0
    {
15279
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
15280
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
15281
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
15282
0
    }
15283
0
    else
15284
0
    {
15285
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
15286
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
15287
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
15288
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
15289
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
15290
0
    }
15291
0
    if (viewport_hovered != NULL)
15292
0
        g.MouseLastHoveredViewport = viewport_hovered;
15293
0
    else if (g.MouseLastHoveredViewport == NULL)
15294
0
        g.MouseLastHoveredViewport = g.Viewports[0];
15295
15296
    // Update mouse reference viewport
15297
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
15298
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
15299
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
15300
0
        g.MouseViewport = g.MovingWindow->Viewport;
15301
0
    else
15302
0
        g.MouseViewport = g.MouseLastHoveredViewport;
15303
15304
    // When dragging something, always refer to the last hovered viewport.
15305
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
15306
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
15307
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
15308
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
15309
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
15310
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
15311
0
        viewport_hovered = g.MouseLastHoveredViewport;
15312
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
15313
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
15314
0
            g.MouseViewport = viewport_hovered;
15315
15316
0
    IM_ASSERT(g.MouseViewport != NULL);
15317
0
}
15318
15319
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
15320
static void ImGui::UpdateViewportsEndFrame()
15321
79.1k
{
15322
79.1k
    ImGuiContext& g = *GImGui;
15323
79.1k
    g.PlatformIO.Viewports.resize(0);
15324
158k
    for (int i = 0; i < g.Viewports.Size; i++)
15325
79.1k
    {
15326
79.1k
        ImGuiViewportP* viewport = g.Viewports[i];
15327
79.1k
        viewport->LastPos = viewport->Pos;
15328
79.1k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
15329
0
            if (i > 0) // Always include main viewport in the list
15330
0
                continue;
15331
79.1k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
15332
0
            continue;
15333
79.1k
        if (i > 0)
15334
79.1k
            IM_ASSERT(viewport->Window != NULL);
15335
79.1k
        g.PlatformIO.Viewports.push_back(viewport);
15336
79.1k
    }
15337
79.1k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
15338
79.1k
}
15339
15340
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
15341
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
15342
79.1k
{
15343
79.1k
    ImGuiContext& g = *GImGui;
15344
79.1k
    IM_ASSERT(id != 0);
15345
15346
79.1k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
15347
79.1k
    if (window != NULL)
15348
0
    {
15349
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
15350
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
15351
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
15352
0
            flags |= ImGuiViewportFlags_NoInputs;
15353
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
15354
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15355
0
    }
15356
15357
79.1k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
15358
79.1k
    if (viewport)
15359
79.1k
    {
15360
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
15361
79.1k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15362
79.1k
            viewport->Pos = pos;
15363
79.1k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15364
79.1k
            viewport->Size = size;
15365
79.1k
        viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
15366
79.1k
    }
15367
0
    else
15368
0
    {
15369
        // New viewport
15370
0
        viewport = IM_NEW(ImGuiViewportP)();
15371
0
        viewport->ID = id;
15372
0
        viewport->Idx = g.Viewports.Size;
15373
0
        viewport->Pos = viewport->LastPos = pos;
15374
0
        viewport->Size = size;
15375
0
        viewport->Flags = flags;
15376
0
        UpdateViewportPlatformMonitor(viewport);
15377
0
        g.Viewports.push_back(viewport);
15378
0
        g.ViewportCreatedCount++;
15379
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
15380
15381
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
15382
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
15383
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
15384
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
15385
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
15386
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
15387
15388
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
15389
        // This is so we can select an appropriate font size on the first frame of our window lifetime
15390
0
        if (viewport->PlatformMonitor != -1)
15391
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
15392
0
    }
15393
15394
79.1k
    viewport->Window = window;
15395
79.1k
    viewport->LastFrameActive = g.FrameCount;
15396
79.1k
    viewport->UpdateWorkRect();
15397
79.1k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
15398
15399
79.1k
    if (window != NULL)
15400
0
        window->ViewportOwned = true;
15401
15402
79.1k
    return viewport;
15403
79.1k
}
15404
15405
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
15406
0
{
15407
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
15408
0
    ImGuiContext& g = *GImGui;
15409
0
    for (ImGuiWindow* window : g.Windows)
15410
0
    {
15411
0
        if (window->Viewport != viewport)
15412
0
            continue;
15413
0
        window->Viewport = NULL;
15414
0
        window->ViewportOwned = false;
15415
0
    }
15416
0
    if (viewport == g.MouseLastHoveredViewport)
15417
0
        g.MouseLastHoveredViewport = NULL;
15418
15419
    // Destroy
15420
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15421
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
15422
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
15423
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
15424
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
15425
0
    IM_DELETE(viewport);
15426
0
}
15427
15428
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
15429
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
15430
169k
{
15431
169k
    ImGuiContext& g = *GImGui;
15432
169k
    ImGuiWindowFlags flags = window->Flags;
15433
169k
    window->ViewportAllowPlatformMonitorExtend = -1;
15434
15435
    // Restore main viewport if multi-viewport is not supported by the backend
15436
169k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
15437
169k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15438
169k
    {
15439
169k
        SetWindowViewport(window, main_viewport);
15440
169k
        return;
15441
169k
    }
15442
0
    window->ViewportOwned = false;
15443
15444
    // Appearing popups reset their viewport so they can inherit again
15445
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
15446
0
    {
15447
0
        window->Viewport = NULL;
15448
0
        window->ViewportId = 0;
15449
0
    }
15450
15451
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
15452
0
    {
15453
        // By default inherit from parent window
15454
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
15455
0
            window->Viewport = window->ParentWindow->Viewport;
15456
15457
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
15458
0
        if (window->Viewport == NULL && window->ViewportId != 0)
15459
0
        {
15460
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
15461
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
15462
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
15463
0
        }
15464
0
    }
15465
15466
0
    bool lock_viewport = false;
15467
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
15468
0
    {
15469
        // Code explicitly request a viewport
15470
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
15471
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
15472
0
        if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
15473
0
        {
15474
0
            window->Viewport->Window = window;
15475
0
            window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
15476
0
        }
15477
0
        lock_viewport = true;
15478
0
    }
15479
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
15480
0
    {
15481
        // Always inherit viewport from parent window
15482
0
        if (window->DockNode && window->DockNode->HostWindow)
15483
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
15484
0
        window->Viewport = window->ParentWindow->Viewport;
15485
0
    }
15486
0
    else if (window->DockNode && window->DockNode->HostWindow)
15487
0
    {
15488
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
15489
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
15490
0
    }
15491
0
    else if (flags & ImGuiWindowFlags_Tooltip)
15492
0
    {
15493
0
        window->Viewport = g.MouseViewport;
15494
0
    }
15495
0
    else if (GetWindowAlwaysWantOwnViewport(window))
15496
0
    {
15497
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15498
0
    }
15499
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
15500
0
    {
15501
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
15502
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15503
0
    }
15504
0
    else
15505
0
    {
15506
        // Merge into host viewport?
15507
        // We cannot test window->ViewportOwned as it set lower in the function.
15508
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
15509
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
15510
0
        if (try_to_merge_into_host_viewport)
15511
0
            UpdateTryMergeWindowIntoHostViewports(window);
15512
0
    }
15513
15514
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
15515
0
    if (window->Viewport == NULL)
15516
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
15517
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15518
15519
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
15520
0
    if (!lock_viewport)
15521
0
    {
15522
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
15523
0
        {
15524
            // We need to take account of the possibility that mouse may become invalid.
15525
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
15526
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
15527
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
15528
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
15529
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
15530
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
15531
0
            else
15532
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15533
0
        }
15534
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
15535
0
        {
15536
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
15537
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
15538
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
15539
0
            {
15540
                // Steal/transfer ownership
15541
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
15542
0
                window->Viewport->Window = window;
15543
0
                window->Viewport->ID = window->ID;
15544
0
                window->Viewport->LastNameHash = 0;
15545
0
            }
15546
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
15547
0
            {
15548
                // New viewport
15549
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
15550
0
            }
15551
0
        }
15552
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
15553
0
        {
15554
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
15555
            // Child windows are kept contained within their parent.
15556
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15557
0
        }
15558
0
    }
15559
15560
    // Update flags
15561
0
    window->ViewportOwned = (window == window->Viewport->Window);
15562
0
    window->ViewportId = window->Viewport->ID;
15563
15564
    // If the OS window has a title bar, hide our imgui title bar
15565
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
15566
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
15567
0
}
15568
15569
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
15570
0
{
15571
0
    ImGuiContext& g = *GImGui;
15572
15573
0
    bool viewport_rect_changed = false;
15574
15575
    // Synchronize window --> viewport in most situations
15576
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
15577
0
    if (window->Viewport->PlatformRequestMove)
15578
0
    {
15579
0
        window->Pos = window->Viewport->Pos;
15580
0
        MarkIniSettingsDirty(window);
15581
0
    }
15582
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
15583
0
    {
15584
0
        viewport_rect_changed = true;
15585
0
        window->Viewport->Pos = window->Pos;
15586
0
    }
15587
15588
0
    if (window->Viewport->PlatformRequestResize)
15589
0
    {
15590
0
        window->Size = window->SizeFull = window->Viewport->Size;
15591
0
        MarkIniSettingsDirty(window);
15592
0
    }
15593
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
15594
0
    {
15595
0
        viewport_rect_changed = true;
15596
0
        window->Viewport->Size = window->Size;
15597
0
    }
15598
0
    window->Viewport->UpdateWorkRect();
15599
15600
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
15601
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
15602
0
    if (viewport_rect_changed)
15603
0
        UpdateViewportPlatformMonitor(window->Viewport);
15604
15605
    // Update common viewport flags
15606
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
15607
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
15608
0
    ImGuiWindowFlags window_flags = window->Flags;
15609
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
15610
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
15611
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
15612
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
15613
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
15614
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
15615
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
15616
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
15617
15618
    // Not correct to set modal as topmost because:
15619
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
15620
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
15621
    //if (flags & ImGuiWindowFlags_Modal)
15622
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
15623
15624
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
15625
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
15626
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
15627
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
15628
0
    if (is_short_lived_floating_window && !is_modal)
15629
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
15630
15631
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
15632
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
15633
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
15634
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
15635
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
15636
15637
    // We can also tell the backend that clearing the platform window won't be necessary,
15638
    // as our window background is filling the viewport and we have disabled BgAlpha.
15639
    // FIXME: Work on support for per-viewport transparency (#2766)
15640
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
15641
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
15642
15643
0
    window->Viewport->Flags = viewport_flags;
15644
15645
    // Update parent viewport ID
15646
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
15647
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
15648
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
15649
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
15650
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
15651
0
    else
15652
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
15653
0
}
15654
15655
// Called by user at the end of the main loop, after EndFrame()
15656
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
15657
void ImGui::UpdatePlatformWindows()
15658
0
{
15659
0
    ImGuiContext& g = *GImGui;
15660
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
15661
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
15662
0
    g.FrameCountPlatformEnded = g.FrameCount;
15663
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15664
0
        return;
15665
15666
    // Create/resize/destroy platform windows to match each active viewport.
15667
    // Skip the main viewport (index 0), which is always fully handled by the application!
15668
0
    for (int i = 1; i < g.Viewports.Size; i++)
15669
0
    {
15670
0
        ImGuiViewportP* viewport = g.Viewports[i];
15671
15672
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
15673
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
15674
0
        bool destroy_platform_window = false;
15675
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
15676
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
15677
0
        if (destroy_platform_window)
15678
0
        {
15679
0
            DestroyPlatformWindow(viewport);
15680
0
            continue;
15681
0
        }
15682
15683
        // New windows that appears directly in a new viewport won't always have a size on their first frame
15684
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
15685
0
            continue;
15686
15687
        // Create window
15688
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
15689
0
        if (is_new_platform_window)
15690
0
        {
15691
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15692
0
            g.PlatformIO.Platform_CreateWindow(viewport);
15693
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
15694
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
15695
0
            g.PlatformWindowsCreatedCount++;
15696
0
            viewport->LastNameHash = 0;
15697
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
15698
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
15699
0
            viewport->PlatformWindowCreated = true;
15700
0
        }
15701
15702
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
15703
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
15704
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
15705
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
15706
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
15707
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
15708
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
15709
0
        viewport->LastPlatformPos = viewport->Pos;
15710
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
15711
15712
        // Update title bar (if it changed)
15713
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
15714
0
        {
15715
0
            const char* title_begin = window_for_title->Name;
15716
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
15717
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
15718
0
            if (viewport->LastNameHash != title_hash)
15719
0
            {
15720
0
                char title_end_backup_c = *title_end;
15721
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
15722
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
15723
0
                *title_end = title_end_backup_c;
15724
0
                viewport->LastNameHash = title_hash;
15725
0
            }
15726
0
        }
15727
15728
        // Update alpha (if it changed)
15729
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
15730
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
15731
0
        viewport->LastAlpha = viewport->Alpha;
15732
15733
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
15734
0
        if (g.PlatformIO.Platform_UpdateWindow)
15735
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
15736
15737
0
        if (is_new_platform_window)
15738
0
        {
15739
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
15740
0
            if (g.FrameCount < 3)
15741
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15742
15743
            // Show window
15744
0
            g.PlatformIO.Platform_ShowWindow(viewport);
15745
15746
            // Even without focus, we assume the window becomes front-most.
15747
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
15748
0
            if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15749
0
                viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15750
0
        }
15751
15752
        // Clear request flags
15753
0
        viewport->ClearRequestFlags();
15754
0
    }
15755
0
}
15756
15757
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
15758
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
15759
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
15760
//
15761
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15762
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15763
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15764
//            MyRenderFunction(platform_io.Viewports[i], my_args);
15765
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15766
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15767
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
15768
//
15769
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
15770
0
{
15771
    // Skip the main viewport (index 0), which is always fully handled by the application!
15772
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15773
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15774
0
    {
15775
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15776
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15777
0
            continue;
15778
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
15779
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
15780
0
    }
15781
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15782
0
    {
15783
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15784
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15785
0
            continue;
15786
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
15787
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
15788
0
    }
15789
0
}
15790
15791
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
15792
0
{
15793
0
    ImGuiContext& g = *GImGui;
15794
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
15795
0
    {
15796
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15797
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
15798
0
            return monitor_n;
15799
0
    }
15800
0
    return -1;
15801
0
}
15802
15803
// Search for the monitor with the largest intersection area with the given rectangle
15804
// We generally try to avoid searching loops but the monitor count should be very small here
15805
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
15806
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
15807
79.1k
{
15808
79.1k
    ImGuiContext& g = *GImGui;
15809
15810
79.1k
    const int monitor_count = g.PlatformIO.Monitors.Size;
15811
79.1k
    if (monitor_count <= 1)
15812
79.1k
        return monitor_count - 1;
15813
15814
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
15815
    // This is necessary for tooltips which always resize down to zero at first.
15816
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
15817
0
    int best_monitor_n = -1;
15818
0
    float best_monitor_surface = 0.001f;
15819
15820
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
15821
0
    {
15822
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15823
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
15824
0
        if (monitor_rect.Contains(rect))
15825
0
            return monitor_n;
15826
0
        ImRect overlapping_rect = rect;
15827
0
        overlapping_rect.ClipWithFull(monitor_rect);
15828
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
15829
0
        if (overlapping_surface < best_monitor_surface)
15830
0
            continue;
15831
0
        best_monitor_surface = overlapping_surface;
15832
0
        best_monitor_n = monitor_n;
15833
0
    }
15834
0
    return best_monitor_n;
15835
0
}
15836
15837
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
15838
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
15839
79.1k
{
15840
79.1k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
15841
79.1k
}
15842
15843
// Return value is always != NULL, but don't hold on it across frames.
15844
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
15845
0
{
15846
0
    ImGuiContext& g = *GImGui;
15847
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
15848
0
    int monitor_idx = viewport->PlatformMonitor;
15849
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
15850
0
        return &g.PlatformIO.Monitors[monitor_idx];
15851
0
    return &g.FallbackMonitor;
15852
0
}
15853
15854
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
15855
0
{
15856
0
    ImGuiContext& g = *GImGui;
15857
0
    if (viewport->PlatformWindowCreated)
15858
0
    {
15859
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15860
0
        if (g.PlatformIO.Renderer_DestroyWindow)
15861
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
15862
0
        if (g.PlatformIO.Platform_DestroyWindow)
15863
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
15864
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
15865
15866
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
15867
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
15868
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
15869
0
            viewport->PlatformWindowCreated = false;
15870
0
    }
15871
0
    else
15872
0
    {
15873
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
15874
0
    }
15875
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
15876
0
    viewport->ClearRequestFlags();
15877
0
}
15878
15879
void ImGui::DestroyPlatformWindows()
15880
0
{
15881
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
15882
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
15883
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
15884
    // code to operator a consistent manner.
15885
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
15886
    // crashing if it doesn't have data stored.
15887
0
    ImGuiContext& g = *GImGui;
15888
0
    for (ImGuiViewportP* viewport : g.Viewports)
15889
0
        DestroyPlatformWindow(viewport);
15890
0
}
15891
15892
15893
//-----------------------------------------------------------------------------
15894
// [SECTION] DOCKING
15895
//-----------------------------------------------------------------------------
15896
// Docking: Internal Types
15897
// Docking: Forward Declarations
15898
// Docking: ImGuiDockContext
15899
// Docking: ImGuiDockContext Docking/Undocking functions
15900
// Docking: ImGuiDockNode
15901
// Docking: ImGuiDockNode Tree manipulation functions
15902
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
15903
// Docking: Builder Functions
15904
// Docking: Begin/End Support Functions (called from Begin/End)
15905
// Docking: Settings
15906
//-----------------------------------------------------------------------------
15907
15908
//-----------------------------------------------------------------------------
15909
// Typical Docking call flow: (root level is generally public API):
15910
//-----------------------------------------------------------------------------
15911
// - NewFrame()                               new dear imgui frame
15912
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
15913
//    | - DockContextProcessUndockWindow()    - process one window undocking request
15914
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
15915
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
15916
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
15917
//    | - DockContextProcessDock()            - process one docking request
15918
//    | - DockNodeUpdate()
15919
//    |   - DockNodeUpdateForRootNode()
15920
//    |     - DockNodeUpdateFlagsAndCollapse()
15921
//    |     - DockNodeFindInfo()
15922
//    |   - destroy unused node or tab bar
15923
//    |   - create dock node host window
15924
//    |      - Begin() etc.
15925
//    |   - DockNodeStartMouseMovingWindow()
15926
//    |   - DockNodeTreeUpdatePosSize()
15927
//    |   - DockNodeTreeUpdateSplitter()
15928
//    |   - draw node background
15929
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
15930
//    |     - DockNodeAddTabBar()
15931
//    |     - DockNodeWindowMenuUpdate()
15932
//    |     - DockNodeCalcTabBarLayout()
15933
//    |     - BeginTabBarEx()
15934
//    |     - TabItemEx() calls
15935
//    |     - EndTabBar()
15936
//    |   - BeginDockableDragDropTarget()
15937
//    |      - DockNodeUpdate()               - recurse into child nodes...
15938
//-----------------------------------------------------------------------------
15939
// - DockSpace()                              user submit a dockspace into a window
15940
//    | Begin(Child)                          - create a child window
15941
//    | DockNodeUpdate()                      - call main dock node update function
15942
//    | End(Child)
15943
//    | ItemSize()
15944
//-----------------------------------------------------------------------------
15945
// - Begin()
15946
//    | BeginDocked()
15947
//    | BeginDockableDragDropSource()
15948
//    | BeginDockableDragDropTarget()
15949
//    | - DockNodePreviewDockRender()
15950
//-----------------------------------------------------------------------------
15951
// - EndFrame()
15952
//    | DockContextEndFrame()
15953
//-----------------------------------------------------------------------------
15954
15955
//-----------------------------------------------------------------------------
15956
// Docking: Internal Types
15957
//-----------------------------------------------------------------------------
15958
// - ImGuiDockRequestType
15959
// - ImGuiDockRequest
15960
// - ImGuiDockPreviewData
15961
// - ImGuiDockNodeSettings
15962
// - ImGuiDockContext
15963
//-----------------------------------------------------------------------------
15964
15965
enum ImGuiDockRequestType
15966
{
15967
    ImGuiDockRequestType_None = 0,
15968
    ImGuiDockRequestType_Dock,
15969
    ImGuiDockRequestType_Undock,
15970
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
15971
};
15972
15973
struct ImGuiDockRequest
15974
{
15975
    ImGuiDockRequestType    Type;
15976
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
15977
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
15978
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
15979
    ImGuiDir                DockSplitDir;
15980
    float                   DockSplitRatio;
15981
    bool                    DockSplitOuter;
15982
    ImGuiWindow*            UndockTargetWindow;
15983
    ImGuiDockNode*          UndockTargetNode;
15984
15985
    ImGuiDockRequest()
15986
0
    {
15987
0
        Type = ImGuiDockRequestType_None;
15988
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
15989
0
        DockTargetNode = UndockTargetNode = NULL;
15990
0
        DockSplitDir = ImGuiDir_None;
15991
0
        DockSplitRatio = 0.5f;
15992
0
        DockSplitOuter = false;
15993
0
    }
15994
};
15995
15996
struct ImGuiDockPreviewData
15997
{
15998
    ImGuiDockNode   FutureNode;
15999
    bool            IsDropAllowed;
16000
    bool            IsCenterAvailable;
16001
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
16002
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
16003
    ImGuiDockNode*  SplitNode;
16004
    ImGuiDir        SplitDir;
16005
    float           SplitRatio;
16006
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
16007
16008
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
16009
};
16010
16011
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
16012
struct ImGuiDockNodeSettings
16013
{
16014
    ImGuiID             ID;
16015
    ImGuiID             ParentNodeId;
16016
    ImGuiID             ParentWindowId;
16017
    ImGuiID             SelectedTabId;
16018
    signed char         SplitAxis;
16019
    char                Depth;
16020
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
16021
    ImVec2ih            Pos;
16022
    ImVec2ih            Size;
16023
    ImVec2ih            SizeRef;
16024
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
16025
};
16026
16027
//-----------------------------------------------------------------------------
16028
// Docking: Forward Declarations
16029
//-----------------------------------------------------------------------------
16030
16031
namespace ImGui
16032
{
16033
    // ImGuiDockContext
16034
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
16035
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
16036
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
16037
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
16038
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
16039
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
16040
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
16041
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
16042
16043
    // ImGuiDockNode
16044
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
16045
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
16046
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
16047
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
16048
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
16049
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
16050
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
16051
    static void             DockNodeUpdate(ImGuiDockNode* node);
16052
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
16053
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
16054
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
16055
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
16056
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
16057
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
16058
    static void             DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
16059
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
16060
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
16061
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
16062
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
16063
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
16064
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
16065
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
16066
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
16067
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
16068
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
16069
16070
    // ImGuiDockNode tree manipulations
16071
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
16072
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
16073
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
16074
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
16075
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
16076
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
16077
16078
    // Settings
16079
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
16080
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
16081
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
16082
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
16083
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
16084
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
16085
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
16086
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
16087
}
16088
16089
//-----------------------------------------------------------------------------
16090
// Docking: ImGuiDockContext
16091
//-----------------------------------------------------------------------------
16092
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
16093
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
16094
// At boot time only, we run a simple GC to remove nodes that have no references.
16095
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
16096
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
16097
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
16098
//-----------------------------------------------------------------------------
16099
// - DockContextInitialize()
16100
// - DockContextShutdown()
16101
// - DockContextClearNodes()
16102
// - DockContextRebuildNodes()
16103
// - DockContextNewFrameUpdateUndocking()
16104
// - DockContextNewFrameUpdateDocking()
16105
// - DockContextEndFrame()
16106
// - DockContextFindNodeByID()
16107
// - DockContextBindNodeToWindow()
16108
// - DockContextGenNodeID()
16109
// - DockContextAddNode()
16110
// - DockContextRemoveNode()
16111
// - ImGuiDockContextPruneNodeData
16112
// - DockContextPruneUnusedSettingsNodes()
16113
// - DockContextBuildNodesFromSettings()
16114
// - DockContextBuildAddWindowsToNodes()
16115
//-----------------------------------------------------------------------------
16116
16117
void ImGui::DockContextInitialize(ImGuiContext* ctx)
16118
1
{
16119
1
    ImGuiContext& g = *ctx;
16120
16121
    // Add .ini handle for persistent docking data
16122
1
    ImGuiSettingsHandler ini_handler;
16123
1
    ini_handler.TypeName = "Docking";
16124
1
    ini_handler.TypeHash = ImHashStr("Docking");
16125
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
16126
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
16127
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
16128
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
16129
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
16130
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
16131
1
    g.SettingsHandlers.push_back(ini_handler);
16132
16133
1
    g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
16134
1
}
16135
16136
void ImGui::DockContextShutdown(ImGuiContext* ctx)
16137
0
{
16138
0
    ImGuiDockContext* dc = &ctx->DockContext;
16139
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
16140
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16141
0
            IM_DELETE(node);
16142
0
}
16143
16144
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
16145
0
{
16146
0
    IM_UNUSED(ctx);
16147
0
    IM_ASSERT(ctx == GImGui);
16148
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
16149
0
    DockBuilderRemoveNodeChildNodes(root_id);
16150
0
}
16151
16152
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
16153
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
16154
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
16155
0
{
16156
0
    ImGuiContext& g = *ctx;
16157
0
    ImGuiDockContext* dc = &ctx->DockContext;
16158
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
16159
0
    SaveIniSettingsToMemory();
16160
0
    ImGuiID root_id = 0; // Rebuild all
16161
0
    DockContextClearNodes(ctx, root_id, false);
16162
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
16163
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
16164
0
}
16165
16166
// Docking context update function, called by NewFrame()
16167
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
16168
79.1k
{
16169
79.1k
    ImGuiContext& g = *ctx;
16170
79.1k
    ImGuiDockContext* dc = &ctx->DockContext;
16171
79.1k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
16172
0
    {
16173
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
16174
0
            DockContextClearNodes(ctx, 0, true);
16175
0
        return;
16176
0
    }
16177
16178
    // Setting NoSplit at runtime merges all nodes
16179
79.1k
    if (g.IO.ConfigDockingNoSplit)
16180
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
16181
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16182
0
                if (node->IsRootNode() && node->IsSplitNode())
16183
0
                {
16184
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
16185
                    //dc->WantFullRebuild = true;
16186
0
                }
16187
16188
    // Process full rebuild
16189
#if 0
16190
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
16191
        dc->WantFullRebuild = true;
16192
#endif
16193
79.1k
    if (dc->WantFullRebuild)
16194
0
    {
16195
0
        DockContextRebuildNodes(ctx);
16196
0
        dc->WantFullRebuild = false;
16197
0
    }
16198
16199
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
16200
79.1k
    for (ImGuiDockRequest& req : dc->Requests)
16201
0
    {
16202
0
        if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
16203
0
            DockContextProcessUndockWindow(ctx, req.UndockTargetWindow);
16204
0
        else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
16205
0
            DockContextProcessUndockNode(ctx, req.UndockTargetNode);
16206
0
    }
16207
79.1k
}
16208
16209
// Docking context update function, called by NewFrame()
16210
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
16211
79.1k
{
16212
79.1k
    ImGuiContext& g = *ctx;
16213
79.1k
    ImGuiDockContext* dc = &ctx->DockContext;
16214
79.1k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
16215
0
        return;
16216
16217
    // [DEBUG] Store hovered dock node.
16218
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
16219
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
16220
79.1k
    g.DebugHoveredDockNode = NULL;
16221
79.1k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
16222
274
    {
16223
274
        if (hovered_window->DockNodeAsHost)
16224
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
16225
274
        else if (hovered_window->RootWindow->DockNode)
16226
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
16227
274
    }
16228
16229
    // Process Docking requests
16230
79.1k
    for (ImGuiDockRequest& req : dc->Requests)
16231
0
        if (req.Type == ImGuiDockRequestType_Dock)
16232
0
            DockContextProcessDock(ctx, &req);
16233
79.1k
    dc->Requests.resize(0);
16234
16235
    // Create windows for each automatic docking nodes
16236
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
16237
79.1k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
16238
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16239
0
            if (node->IsFloatingNode())
16240
0
                DockNodeUpdate(node);
16241
79.1k
}
16242
16243
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
16244
79.1k
{
16245
    // Draw backgrounds of node missing their window
16246
79.1k
    ImGuiContext& g = *ctx;
16247
79.1k
    ImGuiDockContext* dc = &g.DockContext;
16248
79.1k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
16249
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16250
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
16251
0
            {
16252
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
16253
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize);
16254
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16255
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
16256
0
            }
16257
79.1k
}
16258
16259
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
16260
0
{
16261
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
16262
0
}
16263
16264
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
16265
0
{
16266
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
16267
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
16268
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
16269
0
    ImGuiID id = 0x0001;
16270
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
16271
0
        id++;
16272
0
    return id;
16273
0
}
16274
16275
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
16276
0
{
16277
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
16278
0
    ImGuiContext& g = *ctx;
16279
0
    if (id == 0)
16280
0
        id = DockContextGenNodeID(ctx);
16281
0
    else
16282
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
16283
16284
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
16285
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
16286
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
16287
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
16288
0
    return node;
16289
0
}
16290
16291
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
16292
0
{
16293
0
    ImGuiContext& g = *ctx;
16294
0
    ImGuiDockContext* dc = &ctx->DockContext;
16295
16296
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
16297
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
16298
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
16299
0
    IM_ASSERT(node->Windows.Size == 0);
16300
16301
0
    if (node->HostWindow)
16302
0
        node->HostWindow->DockNodeAsHost = NULL;
16303
16304
0
    ImGuiDockNode* parent_node = node->ParentNode;
16305
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
16306
0
    if (merge)
16307
0
    {
16308
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
16309
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
16310
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
16311
0
    }
16312
0
    else
16313
0
    {
16314
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
16315
0
            if (parent_node->ChildNodes[n] == node)
16316
0
                node->ParentNode->ChildNodes[n] = NULL;
16317
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
16318
0
        IM_DELETE(node);
16319
0
    }
16320
0
}
16321
16322
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
16323
0
{
16324
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
16325
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
16326
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
16327
0
}
16328
16329
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
16330
struct ImGuiDockContextPruneNodeData
16331
{
16332
    int         CountWindows, CountChildWindows, CountChildNodes;
16333
    ImGuiID     RootId;
16334
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
16335
};
16336
16337
// Garbage collect unused nodes (run once at init time)
16338
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
16339
0
{
16340
0
    ImGuiContext& g = *ctx;
16341
0
    ImGuiDockContext* dc = &ctx->DockContext;
16342
0
    IM_ASSERT(g.Windows.Size == 0);
16343
16344
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
16345
0
    pool.Reserve(dc->NodesSettings.Size);
16346
16347
    // Count child nodes and compute RootID
16348
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16349
0
    {
16350
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16351
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
16352
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
16353
0
        if (settings->ParentNodeId)
16354
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
16355
0
    }
16356
16357
    // Count reference to dock ids from dockspaces
16358
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
16359
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16360
0
    {
16361
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16362
0
        if (settings->ParentWindowId != 0)
16363
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
16364
0
                if (window_settings->DockId)
16365
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
16366
0
                        data->CountChildNodes++;
16367
0
    }
16368
16369
    // Count reference to dock ids from window settings
16370
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
16371
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
16372
0
        if (ImGuiID dock_id = settings->DockId)
16373
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
16374
0
            {
16375
0
                data->CountWindows++;
16376
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
16377
0
                    data_root->CountChildWindows++;
16378
0
            }
16379
16380
    // Prune
16381
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16382
0
    {
16383
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16384
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
16385
0
        if (data->CountWindows > 1)
16386
0
            continue;
16387
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
16388
16389
0
        bool remove = false;
16390
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
16391
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
16392
0
        remove |= (data_root->CountChildWindows == 0);
16393
0
        if (remove)
16394
0
        {
16395
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
16396
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
16397
0
            settings->ID = 0;
16398
0
        }
16399
0
    }
16400
0
}
16401
16402
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
16403
0
{
16404
    // Build nodes
16405
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
16406
0
    {
16407
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
16408
0
        if (settings->ID == 0)
16409
0
            continue;
16410
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
16411
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
16412
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
16413
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
16414
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
16415
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
16416
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
16417
0
            node->ParentNode->ChildNodes[0] = node;
16418
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
16419
0
            node->ParentNode->ChildNodes[1] = node;
16420
0
        node->SelectedTabId = settings->SelectedTabId;
16421
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
16422
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
16423
16424
        // Bind host window immediately if it already exist (in case of a rebuild)
16425
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
16426
0
        char host_window_title[20];
16427
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16428
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
16429
0
    }
16430
0
}
16431
16432
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
16433
0
{
16434
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
16435
0
    ImGuiContext& g = *ctx;
16436
0
    for (ImGuiWindow* window : g.Windows)
16437
0
    {
16438
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
16439
0
            continue;
16440
0
        if (window->DockNode != NULL)
16441
0
            continue;
16442
16443
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
16444
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
16445
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
16446
0
            DockNodeAddWindow(node, window, true);
16447
0
    }
16448
0
}
16449
16450
//-----------------------------------------------------------------------------
16451
// Docking: ImGuiDockContext Docking/Undocking functions
16452
//-----------------------------------------------------------------------------
16453
// - DockContextQueueDock()
16454
// - DockContextQueueUndockWindow()
16455
// - DockContextQueueUndockNode()
16456
// - DockContextQueueNotifyRemovedNode()
16457
// - DockContextProcessDock()
16458
// - DockContextProcessUndockWindow()
16459
// - DockContextProcessUndockNode()
16460
// - DockContextCalcDropPosForDocking()
16461
//-----------------------------------------------------------------------------
16462
16463
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
16464
0
{
16465
0
    IM_ASSERT(target != payload);
16466
0
    ImGuiDockRequest req;
16467
0
    req.Type = ImGuiDockRequestType_Dock;
16468
0
    req.DockTargetWindow = target;
16469
0
    req.DockTargetNode = target_node;
16470
0
    req.DockPayload = payload;
16471
0
    req.DockSplitDir = split_dir;
16472
0
    req.DockSplitRatio = split_ratio;
16473
0
    req.DockSplitOuter = split_outer;
16474
0
    ctx->DockContext.Requests.push_back(req);
16475
0
}
16476
16477
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
16478
0
{
16479
0
    ImGuiDockRequest req;
16480
0
    req.Type = ImGuiDockRequestType_Undock;
16481
0
    req.UndockTargetWindow = window;
16482
0
    ctx->DockContext.Requests.push_back(req);
16483
0
}
16484
16485
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16486
0
{
16487
0
    ImGuiDockRequest req;
16488
0
    req.Type = ImGuiDockRequestType_Undock;
16489
0
    req.UndockTargetNode = node;
16490
0
    ctx->DockContext.Requests.push_back(req);
16491
0
}
16492
16493
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
16494
0
{
16495
0
    ImGuiDockContext* dc = &ctx->DockContext;
16496
0
    for (ImGuiDockRequest& req : dc->Requests)
16497
0
        if (req.DockTargetNode == node)
16498
0
            req.Type = ImGuiDockRequestType_None;
16499
0
}
16500
16501
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
16502
0
{
16503
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
16504
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
16505
16506
0
    ImGuiContext& g = *ctx;
16507
0
    IM_UNUSED(g);
16508
16509
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
16510
0
    ImGuiWindow* target_window = req->DockTargetWindow;
16511
0
    ImGuiDockNode* node = req->DockTargetNode;
16512
0
    if (payload_window)
16513
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
16514
0
    else
16515
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
16516
16517
    // Decide which Tab will be selected at the end of the operation
16518
0
    ImGuiID next_selected_id = 0;
16519
0
    ImGuiDockNode* payload_node = NULL;
16520
0
    if (payload_window)
16521
0
    {
16522
0
        payload_node = payload_window->DockNodeAsHost;
16523
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
16524
0
        if (payload_node && payload_node->IsLeafNode())
16525
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
16526
0
        if (payload_node == NULL)
16527
0
            next_selected_id = payload_window->TabId;
16528
0
    }
16529
16530
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
16531
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
16532
0
    if (node)
16533
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
16534
0
    if (node && target_window && node == target_window->DockNodeAsHost)
16535
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
16536
16537
    // Create new node and add existing window to it
16538
0
    if (node == NULL)
16539
0
    {
16540
0
        node = DockContextAddNode(ctx, 0);
16541
0
        node->Pos = target_window->Pos;
16542
0
        node->Size = target_window->Size;
16543
0
        if (target_window->DockNodeAsHost == NULL)
16544
0
        {
16545
0
            DockNodeAddWindow(node, target_window, true);
16546
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
16547
0
            target_window->DockIsActive = true;
16548
0
        }
16549
0
    }
16550
16551
0
    ImGuiDir split_dir = req->DockSplitDir;
16552
0
    if (split_dir != ImGuiDir_None)
16553
0
    {
16554
        // Split into two, one side will be our payload node unless we are dropping a loose window
16555
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16556
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
16557
0
        const float split_ratio = req->DockSplitRatio;
16558
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
16559
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
16560
0
        new_node->HostWindow = node->HostWindow;
16561
0
        node = new_node;
16562
0
    }
16563
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16564
16565
0
    if (node != payload_node)
16566
0
    {
16567
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
16568
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
16569
0
        {
16570
0
            DockNodeAddTabBar(node);
16571
0
            for (int n = 0; n < node->Windows.Size; n++)
16572
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16573
0
        }
16574
16575
0
        if (payload_node != NULL)
16576
0
        {
16577
            // Transfer full payload node (with 1+ child windows or child nodes)
16578
0
            if (payload_node->IsSplitNode())
16579
0
            {
16580
0
                if (node->Windows.Size > 0)
16581
0
                {
16582
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
16583
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
16584
                    // This allows us to preserve some of the underlying dock tree settings nicely.
16585
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
16586
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
16587
0
                    if (visible_node->TabBar)
16588
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
16589
0
                    DockNodeMoveWindows(node, visible_node);
16590
0
                    DockNodeMoveWindows(visible_node, node);
16591
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
16592
0
                }
16593
0
                if (node->IsCentralNode())
16594
0
                {
16595
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
16596
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
16597
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
16598
0
                    IM_ASSERT(last_focused_node != NULL);
16599
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
16600
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
16601
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
16602
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
16603
0
                    last_focused_root_node->CentralNode = last_focused_node;
16604
0
                }
16605
16606
0
                IM_ASSERT(node->Windows.Size == 0);
16607
0
                DockNodeMoveChildNodes(node, payload_node);
16608
0
            }
16609
0
            else
16610
0
            {
16611
0
                const ImGuiID payload_dock_id = payload_node->ID;
16612
0
                DockNodeMoveWindows(node, payload_node);
16613
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16614
0
            }
16615
0
            DockContextRemoveNode(ctx, payload_node, true);
16616
0
        }
16617
0
        else if (payload_window)
16618
0
        {
16619
            // Transfer single window
16620
0
            const ImGuiID payload_dock_id = payload_window->DockId;
16621
0
            node->VisibleWindow = payload_window;
16622
0
            DockNodeAddWindow(node, payload_window, true);
16623
0
            if (payload_dock_id != 0)
16624
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16625
0
        }
16626
0
    }
16627
0
    else
16628
0
    {
16629
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
16630
0
        node->WantHiddenTabBarUpdate = true;
16631
0
    }
16632
16633
    // Update selection immediately
16634
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
16635
0
        tab_bar->NextSelectedTabId = next_selected_id;
16636
0
    MarkIniSettingsDirty();
16637
0
}
16638
16639
// Problem:
16640
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
16641
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
16642
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
16643
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
16644
// Solution:
16645
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
16646
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
16647
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
16648
0
{
16649
0
    if (ref_viewport == NULL)
16650
0
        return size;
16651
16652
0
    ImGuiContext& g = *GImGui;
16653
0
    ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f);
16654
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
16655
0
    {
16656
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
16657
0
        max_size = ImTrunc(monitor->WorkSize * 0.90f);
16658
0
    }
16659
0
    return ImMin(size, max_size);
16660
0
}
16661
16662
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
16663
0
{
16664
0
    ImGuiContext& g = *ctx;
16665
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
16666
0
    if (window->DockNode)
16667
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
16668
0
    else
16669
0
        window->DockId = 0;
16670
0
    window->Collapsed = false;
16671
0
    window->DockIsActive = false;
16672
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
16673
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
16674
16675
0
    MarkIniSettingsDirty();
16676
0
}
16677
16678
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16679
0
{
16680
0
    ImGuiContext& g = *ctx;
16681
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
16682
0
    IM_ASSERT(node->IsLeafNode());
16683
0
    IM_ASSERT(node->Windows.Size >= 1);
16684
16685
0
    if (node->IsRootNode() || node->IsCentralNode())
16686
0
    {
16687
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
16688
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
16689
0
        new_node->Pos = node->Pos;
16690
0
        new_node->Size = node->Size;
16691
0
        new_node->SizeRef = node->SizeRef;
16692
0
        DockNodeMoveWindows(new_node, node);
16693
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
16694
0
        node = new_node;
16695
0
    }
16696
0
    else
16697
0
    {
16698
        // Otherwise extract our node and merge our sibling back into the parent node.
16699
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16700
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
16701
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
16702
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
16703
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
16704
0
        node->ParentNode = NULL;
16705
0
    }
16706
0
    for (ImGuiWindow* window : node->Windows)
16707
0
    {
16708
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16709
0
        if (window->ParentWindow)
16710
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
16711
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
16712
0
    }
16713
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
16714
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
16715
0
    node->WantMouseMove = true;
16716
0
    MarkIniSettingsDirty();
16717
0
}
16718
16719
// This is mostly used for automation.
16720
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
16721
0
{
16722
0
    if (target != NULL && target_node == NULL)
16723
0
        target_node = target->DockNode;
16724
16725
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
16726
    // (which would be functionally identical) we only show the outer one. Reflect this here.
16727
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
16728
0
        split_outer = true;
16729
0
    ImGuiDockPreviewData split_data;
16730
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
16731
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
16732
0
        return false;
16733
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
16734
0
    return true;
16735
0
}
16736
16737
//-----------------------------------------------------------------------------
16738
// Docking: ImGuiDockNode
16739
//-----------------------------------------------------------------------------
16740
// - DockNodeGetTabOrder()
16741
// - DockNodeAddWindow()
16742
// - DockNodeRemoveWindow()
16743
// - DockNodeMoveChildNodes()
16744
// - DockNodeMoveWindows()
16745
// - DockNodeApplyPosSizeToWindows()
16746
// - DockNodeHideHostWindow()
16747
// - ImGuiDockNodeFindInfoResults
16748
// - DockNodeFindInfo()
16749
// - DockNodeFindWindowByID()
16750
// - DockNodeUpdateFlagsAndCollapse()
16751
// - DockNodeUpdateHasCentralNodeFlag()
16752
// - DockNodeUpdateVisibleFlag()
16753
// - DockNodeStartMouseMovingWindow()
16754
// - DockNodeUpdate()
16755
// - DockNodeUpdateWindowMenu()
16756
// - DockNodeBeginAmendTabBar()
16757
// - DockNodeEndAmendTabBar()
16758
// - DockNodeUpdateTabBar()
16759
// - DockNodeAddTabBar()
16760
// - DockNodeRemoveTabBar()
16761
// - DockNodeIsDropAllowedOne()
16762
// - DockNodeIsDropAllowed()
16763
// - DockNodeCalcTabBarLayout()
16764
// - DockNodeCalcSplitRects()
16765
// - DockNodeCalcDropRectsAndTestMousePos()
16766
// - DockNodePreviewDockSetup()
16767
// - DockNodePreviewDockRender()
16768
//-----------------------------------------------------------------------------
16769
16770
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
16771
0
{
16772
0
    ID = id;
16773
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
16774
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
16775
0
    TabBar = NULL;
16776
0
    SplitAxis = ImGuiAxis_None;
16777
16778
0
    State = ImGuiDockNodeState_Unknown;
16779
0
    LastBgColor = IM_COL32_WHITE;
16780
0
    HostWindow = VisibleWindow = NULL;
16781
0
    CentralNode = OnlyNodeWithWindows = NULL;
16782
0
    CountNodeWithWindows = 0;
16783
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
16784
0
    LastFocusedNodeId = 0;
16785
0
    SelectedTabId = 0;
16786
0
    WantCloseTabId = 0;
16787
0
    RefViewportId = 0;
16788
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
16789
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
16790
0
    IsVisible = true;
16791
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
16792
0
    IsBgDrawnThisFrame = false;
16793
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
16794
0
}
16795
16796
ImGuiDockNode::~ImGuiDockNode()
16797
0
{
16798
0
    IM_DELETE(TabBar);
16799
0
    TabBar = NULL;
16800
0
    ChildNodes[0] = ChildNodes[1] = NULL;
16801
0
}
16802
16803
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
16804
0
{
16805
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
16806
0
    if (tab_bar == NULL)
16807
0
        return -1;
16808
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
16809
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
16810
0
}
16811
16812
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
16813
0
{
16814
0
    window->Hidden = true;
16815
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
16816
0
}
16817
16818
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
16819
0
{
16820
0
    ImGuiContext& g = *GImGui; (void)g;
16821
0
    if (window->DockNode)
16822
0
    {
16823
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
16824
0
        IM_ASSERT(window->DockNode->ID != node->ID);
16825
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
16826
0
    }
16827
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
16828
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16829
16830
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
16831
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
16832
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
16833
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
16834
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
16835
16836
0
    node->Windows.push_back(window);
16837
0
    node->WantHiddenTabBarUpdate = true;
16838
0
    window->DockNode = node;
16839
0
    window->DockId = node->ID;
16840
0
    window->DockIsActive = (node->Windows.Size > 1);
16841
0
    window->DockTabWantClose = false;
16842
16843
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
16844
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
16845
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
16846
0
    {
16847
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
16848
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
16849
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
16850
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
16851
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
16852
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
16853
0
    }
16854
16855
    // Add to tab bar if requested
16856
0
    if (add_to_tab_bar)
16857
0
    {
16858
0
        if (node->TabBar == NULL)
16859
0
        {
16860
0
            DockNodeAddTabBar(node);
16861
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
16862
16863
            // Add existing windows
16864
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
16865
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16866
0
        }
16867
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
16868
0
    }
16869
16870
0
    DockNodeUpdateVisibleFlag(node);
16871
16872
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
16873
0
    if (node->HostWindow)
16874
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
16875
0
}
16876
16877
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
16878
0
{
16879
0
    ImGuiContext& g = *GImGui;
16880
0
    IM_ASSERT(window->DockNode == node);
16881
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
16882
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
16883
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
16884
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16885
16886
0
    window->DockNode = NULL;
16887
0
    window->DockIsActive = window->DockTabWantClose = false;
16888
0
    window->DockId = save_dock_id;
16889
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16890
0
    if (window->ParentWindow)
16891
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
16892
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
16893
16894
0
    if (node->HostWindow && node->HostWindow->ViewportOwned)
16895
0
    {
16896
        // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
16897
        // But mid-frame, if we clear viewport we need to mark window as hidden as well.
16898
0
        window->Viewport = NULL;
16899
0
        window->ViewportId = 0;
16900
0
        window->ViewportOwned = false;
16901
0
        window->Hidden = true;
16902
0
    }
16903
16904
    // Remove window
16905
0
    bool erased = false;
16906
0
    for (int n = 0; n < node->Windows.Size; n++)
16907
0
        if (node->Windows[n] == window)
16908
0
        {
16909
0
            node->Windows.erase(node->Windows.Data + n);
16910
0
            erased = true;
16911
0
            break;
16912
0
        }
16913
0
    if (!erased)
16914
0
        IM_ASSERT(erased);
16915
0
    if (node->VisibleWindow == window)
16916
0
        node->VisibleWindow = NULL;
16917
16918
    // Remove tab and possibly tab bar
16919
0
    node->WantHiddenTabBarUpdate = true;
16920
0
    if (node->TabBar)
16921
0
    {
16922
0
        TabBarRemoveTab(node->TabBar, window->TabId);
16923
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
16924
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
16925
0
            DockNodeRemoveTabBar(node);
16926
0
    }
16927
16928
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
16929
0
    {
16930
        // Automatic dock node delete themselves if they are not holding at least one tab
16931
0
        DockContextRemoveNode(&g, node, true);
16932
0
        return;
16933
0
    }
16934
16935
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
16936
0
    {
16937
0
        ImGuiWindow* remaining_window = node->Windows[0];
16938
        // Note: we used to transport viewport ownership here.
16939
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
16940
0
    }
16941
16942
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
16943
0
    DockNodeUpdateVisibleFlag(node);
16944
0
}
16945
16946
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16947
0
{
16948
0
    IM_ASSERT(dst_node->Windows.Size == 0);
16949
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
16950
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
16951
0
    if (dst_node->ChildNodes[0])
16952
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
16953
0
    if (dst_node->ChildNodes[1])
16954
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
16955
0
    dst_node->SplitAxis = src_node->SplitAxis;
16956
0
    dst_node->SizeRef = src_node->SizeRef;
16957
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
16958
0
}
16959
16960
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16961
0
{
16962
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
16963
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
16964
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
16965
0
    if (src_tab_bar != NULL)
16966
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
16967
16968
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
16969
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
16970
0
    if (move_tab_bar)
16971
0
    {
16972
0
        dst_node->TabBar = src_node->TabBar;
16973
0
        src_node->TabBar = NULL;
16974
0
    }
16975
16976
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
16977
0
    for (ImGuiWindow* window : src_node->Windows)
16978
0
    {
16979
0
        window->DockNode = NULL;
16980
0
        window->DockIsActive = false;
16981
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
16982
0
    }
16983
0
    src_node->Windows.clear();
16984
16985
0
    if (!move_tab_bar && src_node->TabBar)
16986
0
    {
16987
0
        if (dst_node->TabBar)
16988
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
16989
0
        DockNodeRemoveTabBar(src_node);
16990
0
    }
16991
0
}
16992
16993
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
16994
0
{
16995
0
    for (ImGuiWindow* window : node->Windows)
16996
0
    {
16997
0
        SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
16998
0
        SetWindowSize(window, node->Size, ImGuiCond_Always);
16999
0
    }
17000
0
}
17001
17002
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
17003
0
{
17004
0
    if (node->HostWindow)
17005
0
    {
17006
0
        if (node->HostWindow->DockNodeAsHost == node)
17007
0
            node->HostWindow->DockNodeAsHost = NULL;
17008
0
        node->HostWindow = NULL;
17009
0
    }
17010
17011
0
    if (node->Windows.Size == 1)
17012
0
    {
17013
0
        node->VisibleWindow = node->Windows[0];
17014
0
        node->Windows[0]->DockIsActive = false;
17015
0
    }
17016
17017
0
    if (node->TabBar)
17018
0
        DockNodeRemoveTabBar(node);
17019
0
}
17020
17021
// Search function called once by root node in DockNodeUpdate()
17022
struct ImGuiDockNodeTreeInfo
17023
{
17024
    ImGuiDockNode*      CentralNode;
17025
    ImGuiDockNode*      FirstNodeWithWindows;
17026
    int                 CountNodesWithWindows;
17027
    //ImGuiWindowClass  WindowClassForMerges;
17028
17029
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
17030
};
17031
17032
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
17033
0
{
17034
0
    if (node->Windows.Size > 0)
17035
0
    {
17036
0
        if (info->FirstNodeWithWindows == NULL)
17037
0
            info->FirstNodeWithWindows = node;
17038
0
        info->CountNodesWithWindows++;
17039
0
    }
17040
0
    if (node->IsCentralNode())
17041
0
    {
17042
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
17043
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
17044
0
        info->CentralNode = node;
17045
0
    }
17046
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
17047
0
        return;
17048
0
    if (node->ChildNodes[0])
17049
0
        DockNodeFindInfo(node->ChildNodes[0], info);
17050
0
    if (node->ChildNodes[1])
17051
0
        DockNodeFindInfo(node->ChildNodes[1], info);
17052
0
}
17053
17054
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
17055
0
{
17056
0
    IM_ASSERT(id != 0);
17057
0
    for (ImGuiWindow* window : node->Windows)
17058
0
        if (window->ID == id)
17059
0
            return window;
17060
0
    return NULL;
17061
0
}
17062
17063
// - Remove inactive windows/nodes.
17064
// - Update visibility flag.
17065
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
17066
0
{
17067
0
    ImGuiContext& g = *GImGui;
17068
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
17069
17070
    // Inherit most flags
17071
0
    if (node->ParentNode)
17072
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17073
17074
    // Recurse into children
17075
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
17076
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
17077
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
17078
0
    node->HasCentralNodeChild = false;
17079
0
    if (node->ChildNodes[0])
17080
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
17081
0
    if (node->ChildNodes[1])
17082
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
17083
17084
    // Remove inactive windows, collapse nodes
17085
    // Merge node flags overrides stored in windows
17086
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
17087
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17088
0
    {
17089
0
        ImGuiWindow* window = node->Windows[window_n];
17090
0
        IM_ASSERT(window->DockNode == node);
17091
17092
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
17093
0
        bool remove = false;
17094
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
17095
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
17096
0
        remove |= (window->DockTabWantClose);
17097
0
        if (remove)
17098
0
        {
17099
0
            window->DockTabWantClose = false;
17100
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
17101
0
            {
17102
0
                DockNodeHideHostWindow(node);
17103
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
17104
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
17105
0
                return;
17106
0
            }
17107
0
            DockNodeRemoveWindow(node, window, node->ID);
17108
0
            window_n--;
17109
0
            continue;
17110
0
        }
17111
17112
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
17113
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
17114
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
17115
0
    }
17116
0
    node->UpdateMergedFlags();
17117
17118
    // Auto-hide tab bar option
17119
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
17120
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
17121
0
        node->WantHiddenTabBarToggle = true;
17122
0
    node->WantHiddenTabBarUpdate = false;
17123
17124
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
17125
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
17126
0
        node->WantHiddenTabBarToggle = false;
17127
17128
    // Apply toggles at a single point of the frame (here!)
17129
0
    if (node->Windows.Size > 1)
17130
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
17131
0
    else if (node->WantHiddenTabBarToggle)
17132
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
17133
0
    node->WantHiddenTabBarToggle = false;
17134
17135
0
    DockNodeUpdateVisibleFlag(node);
17136
0
}
17137
17138
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
17139
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
17140
0
{
17141
0
    node->HasCentralNodeChild = false;
17142
0
    if (node->ChildNodes[0])
17143
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
17144
0
    if (node->ChildNodes[1])
17145
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
17146
0
    if (node->IsRootNode())
17147
0
    {
17148
0
        ImGuiDockNode* mark_node = node->CentralNode;
17149
0
        while (mark_node)
17150
0
        {
17151
0
            mark_node->HasCentralNodeChild = true;
17152
0
            mark_node = mark_node->ParentNode;
17153
0
        }
17154
0
    }
17155
0
}
17156
17157
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
17158
0
{
17159
    // Update visibility flag
17160
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
17161
0
    is_visible |= (node->Windows.Size > 0);
17162
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
17163
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
17164
0
    node->IsVisible = is_visible;
17165
0
}
17166
17167
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
17168
0
{
17169
0
    ImGuiContext& g = *GImGui;
17170
0
    IM_ASSERT(node->WantMouseMove == true);
17171
0
    StartMouseMovingWindow(window);
17172
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
17173
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
17174
0
    node->WantMouseMove = false;
17175
0
}
17176
17177
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
17178
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
17179
0
{
17180
0
    DockNodeUpdateFlagsAndCollapse(node);
17181
17182
    // - Setup central node pointers
17183
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
17184
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
17185
0
    ImGuiDockNodeTreeInfo info;
17186
0
    DockNodeFindInfo(node, &info);
17187
0
    node->CentralNode = info.CentralNode;
17188
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
17189
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
17190
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
17191
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
17192
17193
    // Copy the window class from of our first window so it can be used for proper dock filtering.
17194
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
17195
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
17196
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
17197
0
    {
17198
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
17199
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
17200
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
17201
0
            {
17202
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
17203
0
                break;
17204
0
            }
17205
0
    }
17206
17207
0
    ImGuiDockNode* mark_node = node->CentralNode;
17208
0
    while (mark_node)
17209
0
    {
17210
0
        mark_node->HasCentralNodeChild = true;
17211
0
        mark_node = mark_node->ParentNode;
17212
0
    }
17213
0
}
17214
17215
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
17216
0
{
17217
    // Remove ourselves from any previous different host window
17218
    // This can happen if a user mistakenly does (see #4295 for details):
17219
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
17220
    //  - N+1: NewFrame()                   // will create floating host window for that node
17221
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
17222
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
17223
0
        node->HostWindow->DockNodeAsHost = NULL;
17224
17225
0
    host_window->DockNodeAsHost = node;
17226
0
    node->HostWindow = host_window;
17227
0
}
17228
17229
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
17230
0
{
17231
0
    ImGuiContext& g = *GImGui;
17232
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
17233
0
    node->LastFrameAlive = g.FrameCount;
17234
0
    node->IsBgDrawnThisFrame = false;
17235
17236
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
17237
0
    if (node->IsRootNode())
17238
0
        DockNodeUpdateForRootNode(node);
17239
17240
    // Remove tab bar if not needed
17241
0
    if (node->TabBar && node->IsNoTabBar())
17242
0
        DockNodeRemoveTabBar(node);
17243
17244
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
17245
0
    bool want_to_hide_host_window = false;
17246
0
    if (node->IsFloatingNode())
17247
0
    {
17248
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
17249
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
17250
0
                want_to_hide_host_window = true;
17251
0
        if (node->CountNodeWithWindows == 0)
17252
0
            want_to_hide_host_window = true;
17253
0
    }
17254
0
    if (want_to_hide_host_window)
17255
0
    {
17256
0
        if (node->Windows.Size == 1)
17257
0
        {
17258
            // Floating window pos/size is authoritative
17259
0
            ImGuiWindow* single_window = node->Windows[0];
17260
0
            node->Pos = single_window->Pos;
17261
0
            node->Size = single_window->SizeFull;
17262
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
17263
17264
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
17265
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
17266
0
                FocusWindow(single_window);
17267
0
            if (node->HostWindow)
17268
0
            {
17269
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name);
17270
0
                single_window->Viewport = node->HostWindow->Viewport;
17271
0
                single_window->ViewportId = node->HostWindow->ViewportId;
17272
0
                if (node->HostWindow->ViewportOwned)
17273
0
                {
17274
0
                    single_window->Viewport->ID = single_window->ID;
17275
0
                    single_window->Viewport->Window = single_window;
17276
0
                    single_window->ViewportOwned = true;
17277
0
                }
17278
0
            }
17279
0
            node->RefViewportId = single_window->ViewportId;
17280
0
        }
17281
17282
0
        DockNodeHideHostWindow(node);
17283
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
17284
0
        node->WantCloseAll = false;
17285
0
        node->WantCloseTabId = 0;
17286
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
17287
0
        node->LastFrameActive = g.FrameCount;
17288
17289
0
        if (node->WantMouseMove && node->Windows.Size == 1)
17290
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
17291
0
        return;
17292
0
    }
17293
17294
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
17295
    // while the expected visible window is resizing itself.
17296
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
17297
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
17298
    //   N+0: Begin(): window created (with no known size), node is created
17299
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
17300
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
17301
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
17302
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
17303
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
17304
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
17305
0
    {
17306
0
        IM_ASSERT(node->Windows.Size > 0);
17307
0
        ImGuiWindow* ref_window = NULL;
17308
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
17309
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
17310
0
        if (ref_window == NULL)
17311
0
            ref_window = node->Windows[0];
17312
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
17313
0
        {
17314
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
17315
0
            return;
17316
0
        }
17317
0
    }
17318
17319
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
17320
17321
    // Decide if the node will have a close button and a window menu button
17322
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
17323
0
    node->HasCloseButton = false;
17324
0
    for (ImGuiWindow* window : node->Windows)
17325
0
    {
17326
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
17327
0
        node->HasCloseButton |= window->HasCloseButton;
17328
0
        window->DockIsActive = (node->Windows.Size > 1);
17329
0
    }
17330
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
17331
0
        node->HasCloseButton = false;
17332
17333
    // Bind or create host window
17334
0
    ImGuiWindow* host_window = NULL;
17335
0
    bool beginned_into_host_window = false;
17336
0
    if (node->IsDockSpace())
17337
0
    {
17338
        // [Explicit root dockspace node]
17339
0
        IM_ASSERT(node->HostWindow);
17340
0
        host_window = node->HostWindow;
17341
0
    }
17342
0
    else
17343
0
    {
17344
        // [Automatic root or child nodes]
17345
0
        if (node->IsRootNode() && node->IsVisible)
17346
0
        {
17347
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
17348
17349
            // Sync Pos
17350
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
17351
0
                SetNextWindowPos(ref_window->Pos);
17352
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
17353
0
                SetNextWindowPos(node->Pos);
17354
17355
            // Sync Size
17356
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17357
0
                SetNextWindowSize(ref_window->SizeFull);
17358
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
17359
0
                SetNextWindowSize(node->Size);
17360
17361
            // Sync Collapsed
17362
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17363
0
                SetNextWindowCollapsed(ref_window->Collapsed);
17364
17365
            // Sync Viewport
17366
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
17367
0
                SetNextWindowViewport(ref_window->ViewportId);
17368
0
            else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
17369
0
                SetNextWindowViewport(node->RefViewportId);
17370
17371
0
            SetNextWindowClass(&node->WindowClass);
17372
17373
            // Begin into the host window
17374
0
            char window_label[20];
17375
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
17376
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
17377
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
17378
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
17379
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
17380
17381
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
17382
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
17383
0
            Begin(window_label, NULL, window_flags);
17384
0
            PopStyleVar();
17385
0
            beginned_into_host_window = true;
17386
17387
0
            host_window = g.CurrentWindow;
17388
0
            DockNodeSetupHostWindow(node, host_window);
17389
0
            host_window->DC.CursorPos = host_window->Pos;
17390
0
            node->Pos = host_window->Pos;
17391
0
            node->Size = host_window->Size;
17392
17393
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
17394
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
17395
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
17396
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
17397
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
17398
            // after the dock host window, losing their top-most status.
17399
0
            if (node->HostWindow->Appearing)
17400
0
                BringWindowToDisplayFront(node->HostWindow);
17401
17402
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17403
0
        }
17404
0
        else if (node->ParentNode)
17405
0
        {
17406
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
17407
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17408
0
        }
17409
0
        if (node->WantMouseMove && node->HostWindow)
17410
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
17411
0
    }
17412
0
    node->RefViewportId = 0; // Clear when we have a host window
17413
17414
    // Update focused node (the one whose title bar is highlight) within a node tree
17415
0
    if (node->IsSplitNode())
17416
0
        IM_ASSERT(node->TabBar == NULL);
17417
0
    if (node->IsRootNode())
17418
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
17419
0
            while (p_window != NULL && p_window->DockNode != NULL)
17420
0
            {
17421
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
17422
0
                if (p_node == node)
17423
0
                {
17424
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
17425
0
                    break;
17426
0
                }
17427
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
17428
0
            }
17429
17430
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
17431
0
    ImGuiDockNode* central_node = node->CentralNode;
17432
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
17433
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
17434
0
    if (central_node_hole)
17435
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
17436
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
17437
0
                central_node_hole_register_hit_test_hole = false;
17438
0
    if (central_node_hole_register_hit_test_hole)
17439
0
    {
17440
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
17441
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
17442
        // covering passthru node we'd have a gap on the edge not covered by the hole)
17443
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
17444
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
17445
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
17446
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
17447
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
17448
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
17449
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
17450
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
17451
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
17452
0
        if (central_node_hole && !hole_rect.IsInverted())
17453
0
        {
17454
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17455
0
            if (host_window->ParentWindow)
17456
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17457
0
        }
17458
0
    }
17459
17460
    // Update position/size, process and draw resizing splitters
17461
0
    if (node->IsRootNode() && host_window)
17462
0
    {
17463
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
17464
0
        PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]);
17465
0
        PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]);
17466
0
        PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]);
17467
0
        DockNodeTreeUpdateSplitter(node);
17468
0
        PopStyleColor(3);
17469
0
    }
17470
17471
    // Draw empty node background (currently can only be the Central Node)
17472
0
    if (host_window && node->IsEmpty() && node->IsVisible)
17473
0
    {
17474
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17475
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
17476
0
        if (node->LastBgColor != 0)
17477
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
17478
0
        node->IsBgDrawnThisFrame = true;
17479
0
    }
17480
17481
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
17482
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
17483
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
17484
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
17485
0
    if (render_dockspace_bg && node->IsVisible)
17486
0
    {
17487
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17488
0
        if (central_node_hole)
17489
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
17490
0
        else
17491
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
17492
0
    }
17493
17494
    // Draw and populate Tab Bar
17495
0
    if (host_window)
17496
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
17497
0
    if (host_window && node->Windows.Size > 0)
17498
0
    {
17499
0
        DockNodeUpdateTabBar(node, host_window);
17500
0
    }
17501
0
    else
17502
0
    {
17503
0
        node->WantCloseAll = false;
17504
0
        node->WantCloseTabId = 0;
17505
0
        node->IsFocused = false;
17506
0
    }
17507
0
    if (node->TabBar && node->TabBar->SelectedTabId)
17508
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
17509
0
    else if (node->Windows.Size > 0)
17510
0
        node->SelectedTabId = node->Windows[0]->TabId;
17511
17512
    // Draw payload drop target
17513
0
    if (host_window && node->IsVisible)
17514
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
17515
0
            BeginDockableDragDropTarget(host_window);
17516
17517
    // We update this after DockNodeUpdateTabBar()
17518
0
    node->LastFrameActive = g.FrameCount;
17519
17520
    // Recurse into children
17521
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
17522
0
    if (host_window)
17523
0
    {
17524
0
        if (node->ChildNodes[0])
17525
0
            DockNodeUpdate(node->ChildNodes[0]);
17526
0
        if (node->ChildNodes[1])
17527
0
            DockNodeUpdate(node->ChildNodes[1]);
17528
17529
        // Render outer borders last (after the tab bar)
17530
0
        if (node->IsRootNode())
17531
0
            RenderWindowOuterBorders(host_window);
17532
0
    }
17533
17534
    // End host window
17535
0
    if (beginned_into_host_window) //-V1020
17536
0
        End();
17537
0
}
17538
17539
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
17540
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
17541
0
{
17542
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
17543
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
17544
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
17545
0
        return d;
17546
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
17547
0
}
17548
17549
// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
17550
// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
17551
// Custom overrides may want to decorate, group, sort entries.
17552
// Please note those are internal structures: if you copy this expect occasional breakage.
17553
// (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler)
17554
void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17555
0
{
17556
0
    IM_UNUSED(ctx);
17557
0
    if (tab_bar->Tabs.Size == 1)
17558
0
    {
17559
        // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
17560
0
        if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
17561
0
            node->WantHiddenTabBarToggle = true;
17562
0
    }
17563
0
    else
17564
0
    {
17565
        // Display a selectable list of windows in this docking node
17566
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
17567
0
        {
17568
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17569
0
            if (tab->Flags & ImGuiTabItemFlags_Button)
17570
0
                continue;
17571
0
            if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
17572
0
                TabBarQueueFocus(tab_bar, tab);
17573
0
            SameLine();
17574
0
            Text("   ");
17575
0
        }
17576
0
    }
17577
0
}
17578
17579
static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17580
0
{
17581
    // Try to position the menu so it is more likely to stays within the same viewport
17582
0
    ImGuiContext& g = *GImGui;
17583
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
17584
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
17585
0
    else
17586
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
17587
0
    if (BeginPopup("#WindowMenu"))
17588
0
    {
17589
0
        node->IsFocused = true;
17590
0
        g.DockNodeWindowMenuHandler(&g, node, tab_bar);
17591
0
        EndPopup();
17592
0
    }
17593
0
}
17594
17595
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
17596
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
17597
0
{
17598
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
17599
0
        return false;
17600
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
17601
0
        return false;
17602
0
    if (node->TabBar->ID == 0)
17603
0
        return false;
17604
0
    Begin(node->HostWindow->Name);
17605
0
    PushOverrideID(node->ID);
17606
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags);
17607
0
    IM_UNUSED(ret);
17608
0
    IM_ASSERT(ret);
17609
0
    return true;
17610
0
}
17611
17612
void ImGui::DockNodeEndAmendTabBar()
17613
0
{
17614
0
    EndTabBar();
17615
0
    PopID();
17616
0
    End();
17617
0
}
17618
17619
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
17620
0
{
17621
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
17622
0
    ImGuiContext& g = *GImGui;
17623
0
    if (g.NavWindowingTarget)
17624
0
        return (g.NavWindowingTarget->DockNode == node);
17625
17626
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
17627
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
17628
0
    {
17629
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
17630
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
17631
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
17632
0
            parent_window = parent_window->ParentWindow->RootWindow;
17633
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
17634
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
17635
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
17636
0
                return true;
17637
0
    }
17638
0
    return false;
17639
0
}
17640
17641
// Submit the tab bar corresponding to a dock node and various housekeeping details.
17642
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
17643
0
{
17644
0
    ImGuiContext& g = *GImGui;
17645
0
    ImGuiStyle& style = g.Style;
17646
17647
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
17648
0
    const bool closed_all = node->WantCloseAll && node_was_active;
17649
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
17650
0
    node->WantCloseAll = false;
17651
0
    node->WantCloseTabId = 0;
17652
17653
    // Decide if we should use a focused title bar color
17654
0
    bool is_focused = false;
17655
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
17656
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
17657
0
        is_focused = true;
17658
17659
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
17660
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
17661
0
    {
17662
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
17663
0
        node->IsFocused = is_focused;
17664
0
        if (is_focused)
17665
0
            node->LastFrameFocused = g.FrameCount;
17666
0
        if (node->VisibleWindow)
17667
0
        {
17668
            // Notify root of visible window (used to display title in OS task bar)
17669
0
            if (is_focused || root_node->VisibleWindow == NULL)
17670
0
                root_node->VisibleWindow = node->VisibleWindow;
17671
0
            if (node->TabBar)
17672
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
17673
0
        }
17674
0
        return;
17675
0
    }
17676
17677
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
17678
0
    bool backup_skip_item = host_window->SkipItems;
17679
0
    if (!node->IsDockSpace())
17680
0
    {
17681
0
        host_window->SkipItems = false;
17682
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
17683
0
    }
17684
17685
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
17686
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
17687
    // as docked windows themselves will override the stack with their own root ID.
17688
0
    PushOverrideID(node->ID);
17689
0
    ImGuiTabBar* tab_bar = node->TabBar;
17690
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
17691
0
    if (tab_bar == NULL)
17692
0
    {
17693
0
        DockNodeAddTabBar(node);
17694
0
        tab_bar = node->TabBar;
17695
0
    }
17696
17697
0
    ImGuiID focus_tab_id = 0;
17698
0
    node->IsFocused = is_focused;
17699
17700
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
17701
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
17702
17703
    // In a dock node, the Collapse Button turns into the Window Menu button.
17704
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
17705
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
17706
0
    {
17707
0
        ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
17708
0
        DockNodeWindowMenuUpdate(node, tab_bar);
17709
0
        if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
17710
0
            focus_tab_id = tab_bar->NextSelectedTabId;
17711
0
        is_focused |= node->IsFocused;
17712
0
    }
17713
17714
    // Layout
17715
0
    ImRect title_bar_rect, tab_bar_rect;
17716
0
    ImVec2 window_menu_button_pos;
17717
0
    ImVec2 close_button_pos;
17718
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
17719
17720
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
17721
0
    const int tabs_count_old = tab_bar->Tabs.Size;
17722
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17723
0
    {
17724
0
        ImGuiWindow* window = node->Windows[window_n];
17725
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
17726
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
17727
0
    }
17728
17729
    // Title bar
17730
0
    if (is_focused)
17731
0
        node->LastFrameFocused = g.FrameCount;
17732
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
17733
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize);
17734
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
17735
17736
    // Docking/Collapse button
17737
0
    if (has_window_menu_button)
17738
0
    {
17739
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
17740
0
            OpenPopup("#WindowMenu");
17741
0
        if (IsItemActive())
17742
0
            focus_tab_id = tab_bar->SelectedTabId;
17743
0
        if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f)
17744
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingDragToUndockOrMoveNode));
17745
0
    }
17746
17747
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
17748
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
17749
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
17750
0
    {
17751
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
17752
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
17753
0
        tabs_unsorted_start = tab_n;
17754
0
    }
17755
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
17756
0
    {
17757
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
17758
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
17759
0
        {
17760
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17761
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
17762
0
        }
17763
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
17764
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
17765
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
17766
0
    }
17767
17768
    // Apply NavWindow focus back to the tab bar
17769
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
17770
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
17771
17772
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
17773
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
17774
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
17775
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
17776
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
17777
17778
    // Begin tab bar
17779
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
17780
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;// | ImGuiTabBarFlags_FittingPolicyScroll;
17781
0
    tab_bar_flags |= ImGuiTabBarFlags_DrawSelectedOverline;
17782
0
    if (!host_window->Collapsed && is_focused)
17783
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
17784
0
    tab_bar->ID = GetID("#TabBar");
17785
0
    tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
17786
0
    tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
17787
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags);
17788
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
17789
17790
    // Backup style colors
17791
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
17792
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17793
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
17794
17795
    // Submit actual tabs
17796
0
    node->VisibleWindow = NULL;
17797
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17798
0
    {
17799
0
        ImGuiWindow* window = node->Windows[window_n];
17800
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
17801
0
            continue;
17802
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
17803
0
        {
17804
0
            ImGuiTabItemFlags tab_item_flags = 0;
17805
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
17806
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
17807
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
17808
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
17809
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
17810
17811
            // Apply stored style overrides for the window
17812
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17813
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
17814
17815
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
17816
0
            bool tab_open = true;
17817
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
17818
0
            if (!tab_open)
17819
0
                node->WantCloseTabId = window->TabId;
17820
0
            if (tab_bar->VisibleTabId == window->TabId)
17821
0
                node->VisibleWindow = window;
17822
17823
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
17824
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
17825
0
            window->DockTabItemRect = g.LastItemData.Rect;
17826
17827
            // Update navigation ID on menu layer
17828
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
17829
0
                host_window->NavLastIds[1] = window->TabId;
17830
0
        }
17831
0
    }
17832
17833
    // Restore style colors
17834
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17835
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
17836
17837
    // Notify root of visible window (used to display title in OS task bar)
17838
0
    if (node->VisibleWindow)
17839
0
        if (is_focused || root_node->VisibleWindow == NULL)
17840
0
            root_node->VisibleWindow = node->VisibleWindow;
17841
17842
    // Close button (after VisibleWindow was updated)
17843
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
17844
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
17845
0
    const bool close_button_is_visible = node->HasCloseButton;
17846
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
17847
0
    if (close_button_is_visible)
17848
0
    {
17849
0
        if (!close_button_is_enabled)
17850
0
        {
17851
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
17852
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
17853
0
        }
17854
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
17855
0
        {
17856
0
            node->WantCloseAll = true;
17857
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
17858
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
17859
0
        }
17860
        //if (IsItemActive())
17861
        //    focus_tab_id = tab_bar->SelectedTabId;
17862
0
        if (!close_button_is_enabled)
17863
0
        {
17864
0
            PopStyleColor();
17865
0
            PopItemFlag();
17866
0
        }
17867
0
    }
17868
17869
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
17870
    // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
17871
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
17872
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
17873
0
    {
17874
        // AllowOverlap mode required for appending into dock node tab bar,
17875
        // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
17876
0
        bool held;
17877
0
        KeepAliveID(title_bar_id);
17878
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap);
17879
0
        if (g.HoveredId == title_bar_id)
17880
0
        {
17881
0
            g.LastItemData.ID = title_bar_id;
17882
0
        }
17883
0
        if (held)
17884
0
        {
17885
0
            if (IsMouseClicked(0))
17886
0
                focus_tab_id = tab_bar->SelectedTabId;
17887
17888
            // Forward moving request to selected window
17889
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
17890
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); // Undock from tab bar empty space
17891
0
        }
17892
0
    }
17893
17894
    // Forward focus from host node to selected window
17895
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
17896
    //    focus_tab_id = tab_bar->SelectedTabId;
17897
17898
    // When clicked on a tab we requested focus to the docked child
17899
    // This overrides the value set by "forward focus from host node to selected window".
17900
0
    if (tab_bar->NextSelectedTabId)
17901
0
        focus_tab_id = tab_bar->NextSelectedTabId;
17902
17903
    // Apply navigation focus
17904
0
    if (focus_tab_id != 0)
17905
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
17906
0
            if (tab->Window)
17907
0
            {
17908
0
                FocusWindow(tab->Window);
17909
0
                NavInitWindow(tab->Window, false);
17910
0
            }
17911
17912
0
    EndTabBar();
17913
0
    PopID();
17914
17915
    // Restore SkipItems flag
17916
0
    if (!node->IsDockSpace())
17917
0
    {
17918
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
17919
0
        host_window->SkipItems = backup_skip_item;
17920
0
    }
17921
0
}
17922
17923
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
17924
0
{
17925
0
    IM_ASSERT(node->TabBar == NULL);
17926
0
    node->TabBar = IM_NEW(ImGuiTabBar);
17927
0
}
17928
17929
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
17930
0
{
17931
0
    if (node->TabBar == NULL)
17932
0
        return;
17933
0
    IM_DELETE(node->TabBar);
17934
0
    node->TabBar = NULL;
17935
0
}
17936
17937
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
17938
1
{
17939
1
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
17940
0
        return false;
17941
17942
1
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
17943
1
    ImGuiWindowClass* payload_class = &payload->WindowClass;
17944
1
    if (host_class->ClassId != payload_class->ClassId)
17945
0
    {
17946
0
        bool pass = false;
17947
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
17948
0
            pass = true;
17949
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
17950
0
            pass = true;
17951
0
        if (!pass)
17952
0
            return false;
17953
0
    }
17954
17955
    // Prevent docking any window created above a popup
17956
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
17957
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
17958
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
17959
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
17960
1
    ImGuiContext& g = *GImGui;
17961
1
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
17962
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
17963
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
17964
0
                return false;
17965
17966
1
    return true;
17967
1
}
17968
17969
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
17970
1
{
17971
1
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
17972
0
        return true;
17973
17974
1
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
17975
1
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
17976
1
    {
17977
1
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
17978
1
        if (DockNodeIsDropAllowedOne(payload, host_window))
17979
1
            return true;
17980
1
    }
17981
0
    return false;
17982
1
}
17983
17984
// window menu button == collapse button when not in a dock node.
17985
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
17986
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
17987
0
{
17988
0
    ImGuiContext& g = *GImGui;
17989
0
    ImGuiStyle& style = g.Style;
17990
17991
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
17992
0
    if (out_title_rect) { *out_title_rect = r; }
17993
17994
0
    r.Min.x += style.WindowBorderSize;
17995
0
    r.Max.x -= style.WindowBorderSize;
17996
17997
0
    float button_sz = g.FontSize;
17998
0
    r.Min.x += style.FramePadding.x;
17999
0
    r.Max.x -= style.FramePadding.x;
18000
0
    ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
18001
0
    if (node->HasCloseButton)
18002
0
    {
18003
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
18004
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
18005
0
    }
18006
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
18007
0
    {
18008
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
18009
0
    }
18010
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
18011
0
    {
18012
0
        window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
18013
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
18014
0
    }
18015
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
18016
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
18017
0
}
18018
18019
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
18020
0
{
18021
0
    ImGuiContext& g = *GImGui;
18022
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
18023
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
18024
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
18025
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
18026
18027
    // Distribute size on given axis (with a desired size or equally)
18028
0
    const float w_avail = size_old[axis] - dock_spacing;
18029
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
18030
0
    {
18031
0
        size_new[axis] = size_new_desired[axis];
18032
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
18033
0
    }
18034
0
    else
18035
0
    {
18036
0
        size_new[axis] = IM_TRUNC(w_avail * 0.5f);
18037
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
18038
0
    }
18039
18040
    // Position each node
18041
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
18042
0
    {
18043
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
18044
0
    }
18045
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
18046
0
    {
18047
0
        pos_new[axis] = pos_old[axis];
18048
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
18049
0
    }
18050
0
}
18051
18052
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
18053
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
18054
0
{
18055
0
    ImGuiContext& g = *GImGui;
18056
18057
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
18058
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
18059
0
    float hs_w; // Half-size, longer axis
18060
0
    float hs_h; // Half-size, smaller axis
18061
0
    ImVec2 off; // Distance from edge or center
18062
0
    if (outer_docking)
18063
0
    {
18064
        //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
18065
        //hs_h = ImTrunc(hs_w * 0.15f);
18066
        //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
18067
0
        hs_w = ImTrunc(hs_for_central_nodes * 1.50f);
18068
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.80f);
18069
0
        off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
18070
0
    }
18071
0
    else
18072
0
    {
18073
0
        hs_w = ImTrunc(hs_for_central_nodes);
18074
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.90f);
18075
0
        off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f));
18076
0
    }
18077
18078
0
    ImVec2 c = ImTrunc(parent.GetCenter());
18079
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
18080
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
18081
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
18082
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
18083
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
18084
18085
0
    if (test_mouse_pos == NULL)
18086
0
        return false;
18087
18088
0
    ImRect hit_r = out_r;
18089
0
    if (!outer_docking)
18090
0
    {
18091
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
18092
0
        hit_r.Expand(ImTrunc(hs_w * 0.30f));
18093
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
18094
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
18095
0
        float r_threshold_center = hs_w * 1.4f;
18096
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
18097
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
18098
0
            return (dir == ImGuiDir_None);
18099
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
18100
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
18101
0
    }
18102
0
    return hit_r.Contains(*test_mouse_pos);
18103
0
}
18104
18105
// host_node may be NULL if the window doesn't have a DockNode already.
18106
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
18107
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
18108
0
{
18109
0
    ImGuiContext& g = *GImGui;
18110
18111
    // There is an edge case when docking into a dockspace which only has inactive nodes.
18112
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
18113
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
18114
0
    if (payload_node == NULL)
18115
0
        payload_node = payload_window->DockNodeAsHost;
18116
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
18117
0
    if (ref_node_for_rect)
18118
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
18119
18120
    // Filter, figure out where we are allowed to dock
18121
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
18122
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
18123
0
    data->IsCenterAvailable = true;
18124
0
    if (is_outer_docking)
18125
0
        data->IsCenterAvailable = false;
18126
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
18127
0
        data->IsCenterAvailable = false;
18128
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
18129
0
        data->IsCenterAvailable = false;
18130
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
18131
0
        data->IsCenterAvailable = false;
18132
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
18133
0
        data->IsCenterAvailable = false;
18134
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
18135
0
        data->IsCenterAvailable = false;
18136
18137
0
    data->IsSidesAvailable = true;
18138
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
18139
0
        data->IsSidesAvailable = false;
18140
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
18141
0
        data->IsSidesAvailable = false;
18142
0
    else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
18143
0
        data->IsSidesAvailable = false;
18144
18145
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
18146
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
18147
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
18148
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
18149
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
18150
18151
    // Calculate drop shapes geometry for allowed splitting directions
18152
0
    IM_ASSERT(ImGuiDir_None == -1);
18153
0
    data->SplitNode = host_node;
18154
0
    data->SplitDir = ImGuiDir_None;
18155
0
    data->IsSplitDirExplicit = false;
18156
0
    if (!host_window->Collapsed)
18157
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
18158
0
        {
18159
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
18160
0
                continue;
18161
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
18162
0
                continue;
18163
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
18164
0
            {
18165
0
                data->SplitDir = (ImGuiDir)dir;
18166
0
                data->IsSplitDirExplicit = true;
18167
0
            }
18168
0
        }
18169
18170
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
18171
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
18172
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
18173
0
        data->IsDropAllowed = false;
18174
18175
    // Calculate split area
18176
0
    data->SplitRatio = 0.0f;
18177
0
    if (data->SplitDir != ImGuiDir_None)
18178
0
    {
18179
0
        ImGuiDir split_dir = data->SplitDir;
18180
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
18181
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
18182
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
18183
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
18184
18185
        // Calculate split ratio so we can pass it down the docking request
18186
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
18187
0
        data->FutureNode.Pos = pos_new;
18188
0
        data->FutureNode.Size = size_new;
18189
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
18190
0
    }
18191
0
}
18192
18193
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
18194
0
{
18195
0
    ImGuiContext& g = *GImGui;
18196
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
18197
18198
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
18199
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
18200
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
18201
18202
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
18203
0
    int overlay_draw_lists_count = 0;
18204
0
    ImDrawList* overlay_draw_lists[2];
18205
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
18206
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
18207
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
18208
18209
    // Draw main preview rectangle
18210
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
18211
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
18212
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
18213
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
18214
18215
    // Display area preview
18216
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
18217
0
    if (data->IsDropAllowed)
18218
0
    {
18219
0
        ImRect overlay_rect = data->FutureNode.Rect();
18220
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
18221
0
            overlay_rect.Min.y += GetFrameHeight();
18222
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
18223
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
18224
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), g.Style.DockingSeparatorSize));
18225
0
    }
18226
18227
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
18228
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
18229
0
    {
18230
        // Compute target tab bar geometry so we can locate our preview tabs
18231
0
        ImRect tab_bar_rect;
18232
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
18233
0
        ImVec2 tab_pos = tab_bar_rect.Min;
18234
0
        if (host_node && host_node->TabBar)
18235
0
        {
18236
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
18237
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
18238
0
            else
18239
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
18240
0
        }
18241
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
18242
0
        {
18243
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
18244
0
        }
18245
18246
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
18247
0
        if (root_payload->DockNodeAsHost)
18248
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
18249
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
18250
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
18251
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
18252
0
        {
18253
            // DockNode's TabBar may have non-window Tabs manually appended by user
18254
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
18255
0
            if (tab_bar_with_payload && payload_window == NULL)
18256
0
                continue;
18257
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
18258
0
                continue;
18259
18260
            // Calculate the tab bounding box for each payload window
18261
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
18262
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
18263
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
18264
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
18265
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabSelected]);
18266
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
18267
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
18268
0
            {
18269
0
                ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
18270
0
                if (!tab_bar_rect.Contains(tab_bb))
18271
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
18272
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
18273
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
18274
0
                if (!tab_bar_rect.Contains(tab_bb))
18275
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
18276
0
            }
18277
0
            PopStyleColor();
18278
0
        }
18279
0
    }
18280
18281
    // Display drop boxes
18282
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
18283
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
18284
0
    {
18285
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
18286
0
        {
18287
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
18288
0
            ImRect draw_r_in = draw_r;
18289
0
            draw_r_in.Expand(-2.0f);
18290
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
18291
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
18292
0
            {
18293
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
18294
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
18295
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
18296
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
18297
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
18298
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
18299
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
18300
0
            }
18301
0
        }
18302
18303
        // Stop after ImGuiDir_None
18304
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
18305
0
            return;
18306
0
    }
18307
0
}
18308
18309
//-----------------------------------------------------------------------------
18310
// Docking: ImGuiDockNode Tree manipulation functions
18311
//-----------------------------------------------------------------------------
18312
// - DockNodeTreeSplit()
18313
// - DockNodeTreeMerge()
18314
// - DockNodeTreeUpdatePosSize()
18315
// - DockNodeTreeUpdateSplitterFindTouchingNode()
18316
// - DockNodeTreeUpdateSplitter()
18317
// - DockNodeTreeFindFallbackLeafNode()
18318
// - DockNodeTreeFindNodeByPos()
18319
//-----------------------------------------------------------------------------
18320
18321
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
18322
0
{
18323
0
    ImGuiContext& g = *GImGui;
18324
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
18325
18326
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
18327
0
    child_0->ParentNode = parent_node;
18328
18329
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
18330
0
    child_1->ParentNode = parent_node;
18331
18332
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
18333
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
18334
0
    parent_node->ChildNodes[0] = child_0;
18335
0
    parent_node->ChildNodes[1] = child_1;
18336
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
18337
0
    parent_node->SplitAxis = split_axis;
18338
0
    parent_node->VisibleWindow = NULL;
18339
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18340
18341
0
    float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
18342
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
18343
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
18344
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
18345
0
    child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio);
18346
0
    child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]);
18347
18348
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
18349
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
18350
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
18351
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
18352
18353
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
18354
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
18355
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
18356
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18357
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18358
0
    child_0->UpdateMergedFlags();
18359
0
    child_1->UpdateMergedFlags();
18360
0
    parent_node->UpdateMergedFlags();
18361
0
    if (child_inheritor->IsCentralNode())
18362
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
18363
0
}
18364
18365
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
18366
0
{
18367
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
18368
0
    ImGuiContext& g = *GImGui;
18369
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
18370
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
18371
0
    IM_ASSERT(child_0 || child_1);
18372
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
18373
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
18374
0
    {
18375
0
        IM_ASSERT(parent_node->TabBar == NULL);
18376
0
        IM_ASSERT(parent_node->Windows.Size == 0);
18377
0
    }
18378
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
18379
18380
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
18381
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
18382
0
    if (child_0)
18383
0
    {
18384
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
18385
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
18386
0
    }
18387
0
    if (child_1)
18388
0
    {
18389
0
        DockNodeMoveWindows(parent_node, child_1);
18390
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
18391
0
    }
18392
0
    DockNodeApplyPosSizeToWindows(parent_node);
18393
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
18394
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
18395
0
    parent_node->SizeRef = backup_last_explicit_size;
18396
18397
    // Flags transfer
18398
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
18399
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18400
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18401
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
18402
0
    parent_node->UpdateMergedFlags();
18403
18404
0
    if (child_0)
18405
0
    {
18406
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
18407
0
        IM_DELETE(child_0);
18408
0
    }
18409
0
    if (child_1)
18410
0
    {
18411
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
18412
0
        IM_DELETE(child_1);
18413
0
    }
18414
0
}
18415
18416
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
18417
// (Depth-first, Pre-Order)
18418
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
18419
0
{
18420
    // During the regular dock node update we write to all nodes.
18421
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
18422
0
    ImGuiContext& g = *GImGui;
18423
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
18424
0
    if (write_to_node)
18425
0
    {
18426
0
        node->Pos = pos;
18427
0
        node->Size = size;
18428
0
    }
18429
18430
0
    if (node->IsLeafNode())
18431
0
        return;
18432
18433
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
18434
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
18435
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
18436
0
    ImVec2 child_0_size = size, child_1_size = size;
18437
18438
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
18439
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
18440
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
18441
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
18442
18443
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
18444
0
    {
18445
0
        const float spacing = g.Style.DockingSeparatorSize;
18446
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18447
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
18448
18449
        // Size allocation policy
18450
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
18451
0
        const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
18452
18453
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
18454
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
18455
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
18456
18457
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
18458
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
18459
0
        {
18460
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
18461
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18462
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18463
0
        }
18464
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
18465
0
        {
18466
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
18467
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
18468
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18469
0
        }
18470
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
18471
0
        {
18472
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
18473
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
18474
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
18475
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio);
18476
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18477
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18478
0
        }
18479
18480
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
18481
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
18482
0
        {
18483
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
18484
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
18485
0
        }
18486
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
18487
0
        {
18488
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
18489
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
18490
0
        }
18491
0
        else
18492
0
        {
18493
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
18494
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
18495
0
            child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f));
18496
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
18497
0
        }
18498
18499
0
        child_1_pos[axis] += spacing + child_0_size[axis];
18500
0
    }
18501
18502
0
    if (only_write_to_single_node == NULL)
18503
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
18504
18505
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
18506
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
18507
0
    if (child_0_recurse)
18508
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
18509
0
    if (child_1_recurse)
18510
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
18511
0
}
18512
18513
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
18514
0
{
18515
0
    if (node->IsLeafNode())
18516
0
    {
18517
0
        touching_nodes->push_back(node);
18518
0
        return;
18519
0
    }
18520
0
    if (node->ChildNodes[0]->IsVisible)
18521
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
18522
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
18523
0
    if (node->ChildNodes[1]->IsVisible)
18524
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
18525
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
18526
0
}
18527
18528
// (Depth-First, Pre-Order)
18529
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
18530
0
{
18531
0
    if (node->IsLeafNode())
18532
0
        return;
18533
18534
0
    ImGuiContext& g = *GImGui;
18535
18536
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
18537
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
18538
0
    if (child_0->IsVisible && child_1->IsVisible)
18539
0
    {
18540
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
18541
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18542
0
        IM_ASSERT(axis != ImGuiAxis_None);
18543
0
        ImRect bb;
18544
0
        bb.Min = child_0->Pos;
18545
0
        bb.Max = child_1->Pos;
18546
0
        bb.Min[axis] += child_0->Size[axis];
18547
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
18548
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
18549
18550
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
18551
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
18552
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
18553
0
        {
18554
0
            ImGuiWindow* window = g.CurrentWindow;
18555
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
18556
0
        }
18557
0
        else
18558
0
        {
18559
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
18560
            //bb.Max[axis] -= 1;
18561
0
            PushID(node->ID);
18562
18563
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
18564
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
18565
0
            float min_size = g.Style.WindowMinSize[axis];
18566
0
            float resize_limits[2];
18567
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
18568
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
18569
18570
0
            ImGuiID splitter_id = GetID("##Splitter");
18571
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
18572
0
            {
18573
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
18574
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
18575
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
18576
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
18577
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
18578
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
18579
18580
                // [DEBUG] Render touching nodes & limits
18581
                /*
18582
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18583
                for (int n = 0; n < 2; n++)
18584
                {
18585
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
18586
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
18587
                    if (axis == ImGuiAxis_X)
18588
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
18589
                    else
18590
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
18591
                }
18592
                */
18593
0
            }
18594
18595
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
18596
0
            float cur_size_0 = child_0->Size[axis];
18597
0
            float cur_size_1 = child_1->Size[axis];
18598
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
18599
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
18600
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
18601
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
18602
0
            {
18603
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
18604
0
                {
18605
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
18606
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
18607
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
18608
18609
                    // Lock the size of every node that is a sibling of the node we are touching
18610
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
18611
0
                    for (int side_n = 0; side_n < 2; side_n++)
18612
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
18613
0
                        {
18614
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
18615
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18616
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
18617
0
                            while (touching_node->ParentNode != node)
18618
0
                            {
18619
0
                                if (touching_node->ParentNode->SplitAxis == axis)
18620
0
                                {
18621
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
18622
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
18623
0
                                    node_to_preserve->WantLockSizeOnce = true;
18624
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
18625
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
18626
0
                                }
18627
0
                                touching_node = touching_node->ParentNode;
18628
0
                            }
18629
0
                        }
18630
18631
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
18632
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
18633
0
                    MarkIniSettingsDirty();
18634
0
                }
18635
0
            }
18636
0
            PopID();
18637
0
        }
18638
0
    }
18639
18640
0
    if (child_0->IsVisible)
18641
0
        DockNodeTreeUpdateSplitter(child_0);
18642
0
    if (child_1->IsVisible)
18643
0
        DockNodeTreeUpdateSplitter(child_1);
18644
0
}
18645
18646
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
18647
0
{
18648
0
    if (node->IsLeafNode())
18649
0
        return node;
18650
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
18651
0
        return leaf_node;
18652
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
18653
0
        return leaf_node;
18654
0
    return NULL;
18655
0
}
18656
18657
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
18658
0
{
18659
0
    if (!node->IsVisible)
18660
0
        return NULL;
18661
18662
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
18663
0
    ImRect r(node->Pos, node->Pos + node->Size);
18664
0
    r.Expand(dock_spacing * 0.5f);
18665
0
    bool inside = r.Contains(pos);
18666
0
    if (!inside)
18667
0
        return NULL;
18668
18669
0
    if (node->IsLeafNode())
18670
0
        return node;
18671
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
18672
0
        return hovered_node;
18673
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
18674
0
        return hovered_node;
18675
18676
    // This means we are hovering over the splitter/spacing of a parent node
18677
0
    return node;
18678
0
}
18679
18680
//-----------------------------------------------------------------------------
18681
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
18682
//-----------------------------------------------------------------------------
18683
// - SetWindowDock() [Internal]
18684
// - DockSpace()
18685
// - DockSpaceOverViewport()
18686
//-----------------------------------------------------------------------------
18687
18688
// [Internal] Called via SetNextWindowDockID()
18689
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
18690
0
{
18691
    // Test condition (NB: bit 0 is always true) and clear flags for next time
18692
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
18693
0
        return;
18694
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
18695
18696
0
    if (window->DockId == dock_id)
18697
0
        return;
18698
18699
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
18700
0
    ImGuiContext& g = *GImGui;
18701
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(&g, dock_id))
18702
0
        if (new_node->IsSplitNode())
18703
0
        {
18704
            // Policy: Find central node or latest focused node. We first move back to our root node.
18705
0
            new_node = DockNodeGetRootNode(new_node);
18706
0
            if (new_node->CentralNode)
18707
0
            {
18708
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
18709
0
                dock_id = new_node->CentralNode->ID;
18710
0
            }
18711
0
            else
18712
0
            {
18713
0
                dock_id = new_node->LastFocusedNodeId;
18714
0
            }
18715
0
        }
18716
18717
0
    if (window->DockId == dock_id)
18718
0
        return;
18719
18720
0
    if (window->DockNode)
18721
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
18722
0
    window->DockId = dock_id;
18723
0
}
18724
18725
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
18726
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
18727
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
18728
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
18729
ImGuiID ImGui::DockSpace(ImGuiID dockspace_id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
18730
0
{
18731
0
    ImGuiContext& g = *GImGui;
18732
0
    ImGuiWindow* window = GetCurrentWindowRead();
18733
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18734
0
        return 0;
18735
18736
    // Early out if parent window is hidden/collapsed
18737
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
18738
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
18739
0
    if (window->SkipItems)
18740
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
18741
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
18742
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
18743
18744
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
18745
0
    IM_ASSERT(dockspace_id != 0);
18746
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, dockspace_id);
18747
0
    if (node == NULL)
18748
0
    {
18749
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", dockspace_id);
18750
0
        node = DockContextAddNode(&g, dockspace_id);
18751
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
18752
0
    }
18753
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
18754
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", dockspace_id, node->WindowClass.ClassId, window_class->ClassId);
18755
0
    node->SharedFlags = flags;
18756
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
18757
18758
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
18759
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
18760
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
18761
0
    {
18762
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
18763
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18764
0
        return dockspace_id;
18765
0
    }
18766
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18767
18768
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
18769
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
18770
0
    {
18771
0
        node->LastFrameAlive = g.FrameCount;
18772
0
        return dockspace_id;
18773
0
    }
18774
18775
0
    const ImVec2 content_avail = GetContentRegionAvail();
18776
0
    ImVec2 size = ImTrunc(size_arg);
18777
0
    if (size.x <= 0.0f)
18778
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
18779
0
    if (size.y <= 0.0f)
18780
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
18781
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18782
18783
0
    node->Pos = window->DC.CursorPos;
18784
0
    node->Size = node->SizeRef = size;
18785
0
    SetNextWindowPos(node->Pos);
18786
0
    SetNextWindowSize(node->Size);
18787
0
    g.NextWindowData.PosUndock = false;
18788
18789
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
18790
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
18791
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
18792
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
18793
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
18794
0
    window_flags |= ImGuiWindowFlags_NoBackground;
18795
18796
0
    char title[256];
18797
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, dockspace_id);
18798
18799
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
18800
0
    Begin(title, NULL, window_flags);
18801
0
    PopStyleVar();
18802
18803
0
    ImGuiWindow* host_window = g.CurrentWindow;
18804
0
    DockNodeSetupHostWindow(node, host_window);
18805
0
    host_window->ChildId = window->GetID(title);
18806
0
    node->OnlyNodeWithWindows = NULL;
18807
18808
0
    IM_ASSERT(node->IsRootNode());
18809
18810
    // We need to handle the rare case were a central node is missing.
18811
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
18812
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
18813
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
18814
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
18815
    // as it doesn't make sense for an empty dockspace to not have this property.
18816
0
    if (node->IsLeafNode() && !node->IsCentralNode())
18817
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18818
18819
    // Update the node
18820
0
    DockNodeUpdate(node);
18821
18822
0
    End();
18823
18824
0
    ImRect bb(node->Pos, node->Pos + size);
18825
0
    ItemSize(size);
18826
0
    ItemAdd(bb, dockspace_id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
18827
0
    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
18828
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
18829
18830
0
    return dockspace_id;
18831
0
}
18832
18833
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
18834
// The limitation with this call is that your window won't have a local menu bar, but you can also use BeginMainMenuBar().
18835
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
18836
// If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
18837
ImGuiID ImGui::DockSpaceOverViewport(ImGuiID dockspace_id, const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
18838
0
{
18839
0
    if (viewport == NULL)
18840
0
        viewport = GetMainViewport();
18841
18842
    // Submit a window filling the entire viewport
18843
0
    SetNextWindowPos(viewport->WorkPos);
18844
0
    SetNextWindowSize(viewport->WorkSize);
18845
0
    SetNextWindowViewport(viewport->ID);
18846
18847
0
    ImGuiWindowFlags host_window_flags = 0;
18848
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
18849
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
18850
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
18851
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
18852
18853
0
    char label[32];
18854
0
    ImFormatString(label, IM_ARRAYSIZE(label), "WindowOverViewport_%08X", viewport->ID);
18855
18856
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
18857
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
18858
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
18859
0
    Begin(label, NULL, host_window_flags);
18860
0
    PopStyleVar(3);
18861
18862
    // Submit the dockspace
18863
0
    if (dockspace_id == 0)
18864
0
        dockspace_id = GetID("DockSpace");
18865
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
18866
18867
0
    End();
18868
18869
0
    return dockspace_id;
18870
0
}
18871
18872
//-----------------------------------------------------------------------------
18873
// Docking: Builder Functions
18874
//-----------------------------------------------------------------------------
18875
// Very early end-user API to manipulate dock nodes.
18876
// Only available in imgui_internal.h. Expect this API to change/break!
18877
// It is expected that those functions are all called _before_ the dockspace node submission.
18878
//-----------------------------------------------------------------------------
18879
// - DockBuilderDockWindow()
18880
// - DockBuilderGetNode()
18881
// - DockBuilderSetNodePos()
18882
// - DockBuilderSetNodeSize()
18883
// - DockBuilderAddNode()
18884
// - DockBuilderRemoveNode()
18885
// - DockBuilderRemoveNodeChildNodes()
18886
// - DockBuilderRemoveNodeDockedWindows()
18887
// - DockBuilderSplitNode()
18888
// - DockBuilderCopyNodeRec()
18889
// - DockBuilderCopyNode()
18890
// - DockBuilderCopyWindowSettings()
18891
// - DockBuilderCopyDockSpace()
18892
// - DockBuilderFinish()
18893
//-----------------------------------------------------------------------------
18894
18895
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
18896
0
{
18897
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
18898
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18899
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
18900
0
    ImGuiID window_id = ImHashStr(window_name);
18901
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
18902
0
    {
18903
        // Apply to created window
18904
0
        ImGuiID prev_node_id = window->DockId;
18905
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
18906
0
        if (window->DockId != prev_node_id)
18907
0
            window->DockOrder = -1;
18908
0
    }
18909
0
    else
18910
0
    {
18911
        // Apply to settings
18912
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
18913
0
        if (settings == NULL)
18914
0
            settings = CreateNewWindowSettings(window_name);
18915
0
        if (settings->DockId != node_id)
18916
0
            settings->DockOrder = -1;
18917
0
        settings->DockId = node_id;
18918
0
    }
18919
0
}
18920
18921
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
18922
0
{
18923
0
    ImGuiContext& g = *GImGui;
18924
0
    return DockContextFindNodeByID(&g, node_id);
18925
0
}
18926
18927
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
18928
0
{
18929
0
    ImGuiContext& g = *GImGui;
18930
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18931
0
    if (node == NULL)
18932
0
        return;
18933
0
    node->Pos = pos;
18934
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
18935
0
}
18936
18937
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
18938
0
{
18939
0
    ImGuiContext& g = *GImGui;
18940
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18941
0
    if (node == NULL)
18942
0
        return;
18943
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18944
0
    node->Size = node->SizeRef = size;
18945
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18946
0
}
18947
18948
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
18949
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
18950
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
18951
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
18952
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
18953
// - Use (id == 0) to let the system allocate a node identifier.
18954
// - Existing node with a same id will be removed.
18955
ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
18956
0
{
18957
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18958
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
18959
18960
0
    if (node_id != 0)
18961
0
        DockBuilderRemoveNode(node_id);
18962
18963
0
    ImGuiDockNode* node = NULL;
18964
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
18965
0
    {
18966
0
        DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
18967
0
        node = DockContextFindNodeByID(&g, node_id);
18968
0
    }
18969
0
    else
18970
0
    {
18971
0
        node = DockContextAddNode(&g, node_id);
18972
0
        node->SetLocalFlags(flags);
18973
0
    }
18974
0
    node->LastFrameAlive = g.FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
18975
0
    return node->ID;
18976
0
}
18977
18978
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
18979
0
{
18980
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18981
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
18982
18983
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18984
0
    if (node == NULL)
18985
0
        return;
18986
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
18987
0
    DockBuilderRemoveNodeChildNodes(node_id);
18988
    // Node may have moved or deleted if e.g. any merge happened
18989
0
    node = DockContextFindNodeByID(&g, node_id);
18990
0
    if (node == NULL)
18991
0
        return;
18992
0
    if (node->IsCentralNode() && node->ParentNode)
18993
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18994
0
    DockContextRemoveNode(&g, node, true);
18995
0
}
18996
18997
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
18998
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
18999
0
{
19000
0
    ImGuiContext& g = *GImGui;
19001
0
    ImGuiDockContext* dc = &g.DockContext;
19002
19003
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(&g, root_id) : NULL;
19004
0
    if (root_id && root_node == NULL)
19005
0
        return;
19006
0
    bool has_central_node = false;
19007
19008
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
19009
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
19010
19011
    // Process active windows
19012
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
19013
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
19014
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19015
0
        {
19016
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
19017
0
            if (want_removal)
19018
0
            {
19019
0
                if (node->IsCentralNode())
19020
0
                    has_central_node = true;
19021
0
                if (root_id != 0)
19022
0
                    DockContextQueueNotifyRemovedNode(&g, node);
19023
0
                if (root_node)
19024
0
                {
19025
0
                    DockNodeMoveWindows(root_node, node);
19026
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
19027
0
                }
19028
0
                nodes_to_remove.push_back(node);
19029
0
            }
19030
0
        }
19031
19032
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
19033
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
19034
0
    if (root_node)
19035
0
    {
19036
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
19037
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
19038
0
    }
19039
19040
    // Apply to settings
19041
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19042
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
19043
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
19044
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
19045
0
                {
19046
0
                    settings->DockId = root_id;
19047
0
                    break;
19048
0
                }
19049
19050
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
19051
0
    if (nodes_to_remove.Size > 1)
19052
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
19053
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
19054
0
        DockContextRemoveNode(&g, nodes_to_remove[n], false);
19055
19056
0
    if (root_id == 0)
19057
0
    {
19058
0
        dc->Nodes.Clear();
19059
0
        dc->Requests.clear();
19060
0
    }
19061
0
    else if (has_central_node)
19062
0
    {
19063
0
        root_node->CentralNode = root_node;
19064
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
19065
0
    }
19066
0
}
19067
19068
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
19069
0
{
19070
    // Clear references in settings
19071
0
    ImGuiContext& g = *GImGui;
19072
0
    if (clear_settings_refs)
19073
0
    {
19074
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19075
0
        {
19076
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
19077
0
            if (!want_removal && settings->DockId != 0)
19078
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(&g, settings->DockId))
19079
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
19080
0
                        want_removal = true;
19081
0
            if (want_removal)
19082
0
                settings->DockId = 0;
19083
0
        }
19084
0
    }
19085
19086
    // Clear references in windows
19087
0
    for (int n = 0; n < g.Windows.Size; n++)
19088
0
    {
19089
0
        ImGuiWindow* window = g.Windows[n];
19090
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
19091
0
        if (want_removal)
19092
0
        {
19093
0
            const ImGuiID backup_dock_id = window->DockId;
19094
0
            IM_UNUSED(backup_dock_id);
19095
0
            DockContextProcessUndockWindow(&g, window, clear_settings_refs);
19096
0
            if (!clear_settings_refs)
19097
0
                IM_ASSERT(window->DockId == backup_dock_id);
19098
0
        }
19099
0
    }
19100
0
}
19101
19102
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
19103
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
19104
// FIXME-DOCK: We are not exposing nor using split_outer.
19105
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
19106
0
{
19107
0
    ImGuiContext& g = *GImGui;
19108
0
    IM_ASSERT(split_dir != ImGuiDir_None);
19109
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
19110
19111
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
19112
0
    if (node == NULL)
19113
0
    {
19114
0
        IM_ASSERT(node != NULL);
19115
0
        return 0;
19116
0
    }
19117
19118
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
19119
19120
0
    ImGuiDockRequest req;
19121
0
    req.Type = ImGuiDockRequestType_Split;
19122
0
    req.DockTargetWindow = NULL;
19123
0
    req.DockTargetNode = node;
19124
0
    req.DockPayload = NULL;
19125
0
    req.DockSplitDir = split_dir;
19126
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
19127
0
    req.DockSplitOuter = false;
19128
0
    DockContextProcessDock(&g, &req);
19129
19130
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
19131
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
19132
0
    if (out_id_at_dir)
19133
0
        *out_id_at_dir = id_at_dir;
19134
0
    if (out_id_at_opposite_dir)
19135
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
19136
0
    return id_at_dir;
19137
0
}
19138
19139
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
19140
0
{
19141
0
    ImGuiContext& g = *GImGui;
19142
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
19143
0
    dst_node->SharedFlags = src_node->SharedFlags;
19144
0
    dst_node->LocalFlags = src_node->LocalFlags;
19145
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
19146
0
    dst_node->Pos = src_node->Pos;
19147
0
    dst_node->Size = src_node->Size;
19148
0
    dst_node->SizeRef = src_node->SizeRef;
19149
0
    dst_node->SplitAxis = src_node->SplitAxis;
19150
0
    dst_node->UpdateMergedFlags();
19151
19152
0
    out_node_remap_pairs->push_back(src_node->ID);
19153
0
    out_node_remap_pairs->push_back(dst_node->ID);
19154
19155
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
19156
0
        if (src_node->ChildNodes[child_n])
19157
0
        {
19158
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
19159
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
19160
0
        }
19161
19162
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
19163
0
    return dst_node;
19164
0
}
19165
19166
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
19167
0
{
19168
0
    ImGuiContext& g = *GImGui;
19169
0
    IM_ASSERT(src_node_id != 0);
19170
0
    IM_ASSERT(dst_node_id != 0);
19171
0
    IM_ASSERT(out_node_remap_pairs != NULL);
19172
19173
0
    DockBuilderRemoveNode(dst_node_id);
19174
19175
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(&g, src_node_id);
19176
0
    IM_ASSERT(src_node != NULL);
19177
19178
0
    out_node_remap_pairs->clear();
19179
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
19180
19181
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
19182
0
}
19183
19184
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
19185
0
{
19186
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
19187
0
    if (src_window == NULL)
19188
0
        return;
19189
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
19190
0
    {
19191
0
        dst_window->Pos = src_window->Pos;
19192
0
        dst_window->Size = src_window->Size;
19193
0
        dst_window->SizeFull = src_window->SizeFull;
19194
0
        dst_window->Collapsed = src_window->Collapsed;
19195
0
    }
19196
0
    else
19197
0
    {
19198
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
19199
0
        if (!dst_settings)
19200
0
            dst_settings = CreateNewWindowSettings(dst_name);
19201
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
19202
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
19203
0
        {
19204
0
            dst_settings->ViewportPos = window_pos_2ih;
19205
0
            dst_settings->ViewportId = src_window->ViewportId;
19206
0
            dst_settings->Pos = ImVec2ih(0, 0);
19207
0
        }
19208
0
        else
19209
0
        {
19210
0
            dst_settings->Pos = window_pos_2ih;
19211
0
        }
19212
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
19213
0
        dst_settings->Collapsed = src_window->Collapsed;
19214
0
    }
19215
0
}
19216
19217
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
19218
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
19219
0
{
19220
0
    ImGuiContext& g = *GImGui;
19221
0
    IM_ASSERT(src_dockspace_id != 0);
19222
0
    IM_ASSERT(dst_dockspace_id != 0);
19223
0
    IM_ASSERT(in_window_remap_pairs != NULL);
19224
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
19225
19226
    // Duplicate entire dock
19227
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
19228
    // whereas we could attempt to at least keep them together in a new, same floating node.
19229
0
    ImVector<ImGuiID> node_remap_pairs;
19230
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
19231
19232
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
19233
    // (The windows associated to src_dockspace_id are staying in place)
19234
0
    ImVector<ImGuiID> src_windows;
19235
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
19236
0
    {
19237
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
19238
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
19239
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
19240
0
        src_windows.push_back(src_window_id);
19241
19242
        // Search in the remapping tables
19243
0
        ImGuiID src_dock_id = 0;
19244
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
19245
0
            src_dock_id = src_window->DockId;
19246
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
19247
0
            src_dock_id = src_window_settings->DockId;
19248
0
        ImGuiID dst_dock_id = 0;
19249
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
19250
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
19251
0
            {
19252
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
19253
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
19254
0
                break;
19255
0
            }
19256
19257
0
        if (dst_dock_id != 0)
19258
0
        {
19259
            // Docked windows gets redocked into the new node hierarchy.
19260
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
19261
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
19262
0
        }
19263
0
        else
19264
0
        {
19265
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
19266
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
19267
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
19268
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
19269
0
        }
19270
0
    }
19271
19272
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
19273
    // Find those windows and move to them to the cloned dock node. This may be optional?
19274
    // Dock those are a second step as undocking would invalidate source dock nodes.
19275
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
19276
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
19277
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
19278
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
19279
0
        {
19280
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
19281
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
19282
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
19283
0
            {
19284
0
                ImGuiWindow* window = node->Windows[window_n];
19285
0
                if (src_windows.contains(window->ID))
19286
0
                    continue;
19287
19288
                // Docked windows gets redocked into the new node hierarchy.
19289
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
19290
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
19291
0
            }
19292
0
        }
19293
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
19294
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
19295
0
}
19296
19297
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
19298
void ImGui::DockBuilderFinish(ImGuiID root_id)
19299
0
{
19300
0
    ImGuiContext& g = *GImGui;
19301
    //DockContextRebuild(&g);
19302
0
    DockContextBuildAddWindowsToNodes(&g, root_id);
19303
0
}
19304
19305
//-----------------------------------------------------------------------------
19306
// Docking: Begin/End Support Functions (called from Begin/End)
19307
//-----------------------------------------------------------------------------
19308
// - GetWindowAlwaysWantOwnTabBar()
19309
// - DockContextBindNodeToWindow()
19310
// - BeginDocked()
19311
// - BeginDockableDragDropSource()
19312
// - BeginDockableDragDropTarget()
19313
//-----------------------------------------------------------------------------
19314
19315
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
19316
169k
{
19317
169k
    ImGuiContext& g = *GImGui;
19318
169k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
19319
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
19320
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
19321
0
                return true;
19322
169k
    return false;
19323
169k
}
19324
19325
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
19326
0
{
19327
0
    ImGuiContext& g = *ctx;
19328
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
19329
0
    IM_ASSERT(window->DockNode == NULL);
19330
19331
    // We should not be docking into a split node (SetWindowDock should avoid this)
19332
0
    if (node && node->IsSplitNode())
19333
0
    {
19334
0
        DockContextProcessUndockWindow(ctx, window);
19335
0
        return NULL;
19336
0
    }
19337
19338
    // Create node
19339
0
    if (node == NULL)
19340
0
    {
19341
0
        node = DockContextAddNode(ctx, window->DockId);
19342
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
19343
0
        node->LastFrameAlive = g.FrameCount;
19344
0
    }
19345
19346
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
19347
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
19348
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
19349
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
19350
0
    if (!node->IsVisible)
19351
0
    {
19352
0
        ImGuiDockNode* ancestor_node = node;
19353
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
19354
0
            ancestor_node = ancestor_node->ParentNode;
19355
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
19356
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
19357
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
19358
0
    }
19359
19360
    // Add window to node
19361
0
    bool node_was_visible = node->IsVisible;
19362
0
    DockNodeAddWindow(node, window, true);
19363
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
19364
0
    IM_ASSERT(node == window->DockNode);
19365
0
    return node;
19366
0
}
19367
19368
static void StoreDockStyleForWindow(ImGuiWindow* window)
19369
16
{
19370
16
    ImGuiContext& g = *GImGui;
19371
144
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19372
128
        window->DockStyle.Colors[color_n] = ImGui::ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
19373
16
}
19374
19375
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
19376
0
{
19377
0
    ImGuiContext& g = *GImGui;
19378
19379
    // Clear fields ahead so most early-out paths don't have to do it
19380
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
19381
19382
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
19383
0
    if (auto_dock_node)
19384
0
    {
19385
0
        if (window->DockId == 0)
19386
0
        {
19387
0
            IM_ASSERT(window->DockNode == NULL);
19388
0
            window->DockId = DockContextGenNodeID(&g);
19389
0
        }
19390
0
    }
19391
0
    else
19392
0
    {
19393
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
19394
0
        bool want_undock = false;
19395
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
19396
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
19397
0
        if (want_undock)
19398
0
        {
19399
0
            DockContextProcessUndockWindow(&g, window);
19400
0
            return;
19401
0
        }
19402
0
    }
19403
19404
    // Bind to our dock node
19405
0
    ImGuiDockNode* node = window->DockNode;
19406
0
    if (node != NULL)
19407
0
        IM_ASSERT(window->DockId == node->ID);
19408
0
    if (window->DockId != 0 && node == NULL)
19409
0
    {
19410
0
        node = DockContextBindNodeToWindow(&g, window);
19411
0
        if (node == NULL)
19412
0
            return;
19413
0
    }
19414
19415
#if 0
19416
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
19417
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
19418
    {
19419
        DockContextProcessUndockWindow(ctx, window);
19420
        return;
19421
    }
19422
#endif
19423
19424
    // Undock if our dockspace node disappeared
19425
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
19426
0
    if (node->LastFrameAlive < g.FrameCount)
19427
0
    {
19428
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
19429
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
19430
0
        if (root_node->LastFrameAlive < g.FrameCount)
19431
0
            DockContextProcessUndockWindow(&g, window);
19432
0
        else
19433
0
            window->DockIsActive = true;
19434
0
        return;
19435
0
    }
19436
19437
    // Store style overrides
19438
0
    StoreDockStyleForWindow(window);
19439
19440
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
19441
    // and never create neither a host window neither a tab bar.
19442
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
19443
0
    if (node->HostWindow == NULL)
19444
0
    {
19445
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
19446
0
            window->DockIsActive = true;
19447
0
        if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
19448
0
            DockNodeHideWindowDuringHostWindowCreation(window);
19449
0
        return;
19450
0
    }
19451
19452
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
19453
0
    IM_ASSERT(node->HostWindow);
19454
0
    IM_ASSERT(node->IsLeafNode());
19455
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
19456
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
19457
19458
    // Undock if we are submitted earlier than the host window
19459
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
19460
0
    {
19461
0
        DockContextProcessUndockWindow(&g, window);
19462
0
        return;
19463
0
    }
19464
19465
    // Position/Size window
19466
0
    SetNextWindowPos(node->Pos);
19467
0
    SetNextWindowSize(node->Size);
19468
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
19469
0
    window->DockIsActive = true;
19470
0
    window->DockNodeIsVisible = true;
19471
0
    window->DockTabIsVisible = false;
19472
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
19473
0
        return;
19474
19475
    // When the window is selected we mark it as visible.
19476
0
    if (node->VisibleWindow == window)
19477
0
        window->DockTabIsVisible = true;
19478
19479
    // Update window flag
19480
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
19481
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize;
19482
0
    window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding;
19483
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
19484
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
19485
0
    else
19486
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
19487
19488
    // Save new dock order only if the window has been visible once already
19489
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
19490
0
    if (node->TabBar && window->WasActive)
19491
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
19492
19493
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
19494
0
        *p_open = false;
19495
19496
    // Update ChildId to allow returning from Child to Parent with Escape
19497
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
19498
0
    window->ChildId = parent_window->GetID(window->Name);
19499
0
}
19500
19501
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
19502
55
{
19503
55
    ImGuiContext& g = *GImGui;
19504
55
    IM_ASSERT(g.ActiveId == window->MoveId);
19505
55
    IM_ASSERT(g.MovingWindow == window);
19506
55
    IM_ASSERT(g.CurrentWindow == window);
19507
19508
    // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
19509
55
    if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
19510
0
    {
19511
        // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
19512
        // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
19513
        // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
19514
0
        IM_ASSERT(g.NextWindowData.Flags == 0);
19515
0
        if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
19516
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock));
19517
0
        return;
19518
0
    }
19519
19520
55
    g.LastItemData.ID = window->MoveId;
19521
55
    window = window->RootWindowDockTree;
19522
55
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19523
55
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
19524
55
    ImGuiDragDropFlags drag_drop_flags = ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_PayloadAutoExpire | ImGuiDragDropFlags_PayloadNoCrossContext | ImGuiDragDropFlags_PayloadNoCrossProcess;
19525
55
    if (is_drag_docking && BeginDragDropSource(drag_drop_flags))
19526
16
    {
19527
16
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
19528
16
        EndDragDropSource();
19529
16
        StoreDockStyleForWindow(window); // Store style overrides while dragging (even when not docked) because docking preview may need it.
19530
16
    }
19531
55
}
19532
19533
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
19534
22
{
19535
22
    ImGuiContext& g = *GImGui;
19536
19537
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
19538
22
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19539
22
    if (!g.DragDropActive)
19540
0
        return;
19541
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19542
22
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
19543
21
        return;
19544
19545
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
19546
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
19547
1
    const ImGuiPayload* payload = &g.DragDropPayload;
19548
1
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
19549
0
    {
19550
0
        EndDragDropTarget();
19551
0
        return;
19552
0
    }
19553
19554
1
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
19555
1
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
19556
1
    {
19557
        // Select target node
19558
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
19559
1
        bool dock_into_floating_window = false;
19560
1
        ImGuiDockNode* node = NULL;
19561
1
        if (window->DockNodeAsHost)
19562
0
        {
19563
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
19564
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
19565
19566
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
19567
            // In this case we need to fallback into any leaf mode, possibly the central node.
19568
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
19569
0
            if (node && node->IsDockSpace() && node->IsRootNode())
19570
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
19571
0
        }
19572
1
        else
19573
1
        {
19574
1
            if (window->DockNode)
19575
0
                node = window->DockNode;
19576
1
            else
19577
1
                dock_into_floating_window = true; // Dock into a regular window
19578
1
        }
19579
19580
1
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
19581
1
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
19582
19583
        // Preview docking request and find out split direction/ratio
19584
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
19585
1
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
19586
1
        if (do_preview && (node != NULL || dock_into_floating_window))
19587
0
        {
19588
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
19589
0
            ImGuiDockPreviewData split_inner;
19590
0
            ImGuiDockPreviewData split_outer;
19591
0
            ImGuiDockPreviewData* split_data = &split_inner;
19592
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
19593
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
19594
0
                {
19595
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
19596
0
                    if (split_outer.IsSplitDirExplicit)
19597
0
                        split_data = &split_outer;
19598
0
                }
19599
0
            if (!node || node->IsLeafNode())
19600
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
19601
0
            if (split_data == &split_outer)
19602
0
                split_inner.IsDropAllowed = false;
19603
19604
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
19605
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
19606
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
19607
19608
            // Queue docking request
19609
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
19610
0
                DockContextQueueDock(&g, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
19611
0
        }
19612
1
    }
19613
1
    EndDragDropTarget();
19614
1
}
19615
19616
//-----------------------------------------------------------------------------
19617
// Docking: Settings
19618
//-----------------------------------------------------------------------------
19619
// - DockSettingsRenameNodeReferences()
19620
// - DockSettingsRemoveNodeReferences()
19621
// - DockSettingsFindNodeSettings()
19622
// - DockSettingsHandler_ApplyAll()
19623
// - DockSettingsHandler_ReadOpen()
19624
// - DockSettingsHandler_ReadLine()
19625
// - DockSettingsHandler_DockNodeToSettings()
19626
// - DockSettingsHandler_WriteAll()
19627
//-----------------------------------------------------------------------------
19628
19629
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
19630
0
{
19631
0
    ImGuiContext& g = *GImGui;
19632
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
19633
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
19634
0
    {
19635
0
        ImGuiWindow* window = g.Windows[window_n];
19636
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
19637
0
            window->DockId = new_node_id;
19638
0
    }
19639
    //// FIXME-OPT: We could remove this loop by storing the index in the map
19640
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19641
0
        if (settings->DockId == old_node_id)
19642
0
            settings->DockId = new_node_id;
19643
0
}
19644
19645
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
19646
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
19647
0
{
19648
0
    ImGuiContext& g = *GImGui;
19649
0
    int found = 0;
19650
    //// FIXME-OPT: We could remove this loop by storing the index in the map
19651
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19652
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
19653
0
            if (settings->DockId == node_ids[node_n])
19654
0
            {
19655
0
                settings->DockId = 0;
19656
0
                settings->DockOrder = -1;
19657
0
                if (++found < node_ids_count)
19658
0
                    break;
19659
0
                return;
19660
0
            }
19661
0
}
19662
19663
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
19664
0
{
19665
    // FIXME-OPT
19666
0
    ImGuiDockContext* dc = &ctx->DockContext;
19667
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
19668
0
        if (dc->NodesSettings[n].ID == id)
19669
0
            return &dc->NodesSettings[n];
19670
0
    return NULL;
19671
0
}
19672
19673
// Clear settings data
19674
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19675
0
{
19676
0
    ImGuiDockContext* dc = &ctx->DockContext;
19677
0
    dc->NodesSettings.clear();
19678
0
    DockContextClearNodes(ctx, 0, true);
19679
0
}
19680
19681
// Recreate nodes based on settings data
19682
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19683
0
{
19684
    // Prune settings at boot time only
19685
0
    ImGuiDockContext* dc = &ctx->DockContext;
19686
0
    if (ctx->Windows.Size == 0)
19687
0
        DockContextPruneUnusedSettingsNodes(ctx);
19688
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
19689
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
19690
0
}
19691
19692
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
19693
0
{
19694
0
    if (strcmp(name, "Data") != 0)
19695
0
        return NULL;
19696
0
    return (void*)1;
19697
0
}
19698
19699
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
19700
0
{
19701
0
    char c = 0;
19702
0
    int x = 0, y = 0;
19703
0
    int r = 0;
19704
19705
    // Parsing, e.g.
19706
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
19707
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
19708
    // Important: this code expect currently fields in a fixed order.
19709
0
    ImGuiDockNodeSettings node;
19710
0
    line = ImStrSkipBlank(line);
19711
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
19712
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
19713
0
    else return;
19714
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
19715
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
19716
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
19717
0
    if (node.ParentNodeId == 0)
19718
0
    {
19719
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
19720
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
19721
0
    }
19722
0
    else
19723
0
    {
19724
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
19725
0
    }
19726
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
19727
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
19728
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
19729
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
19730
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
19731
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
19732
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
19733
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
19734
0
    if (node.ParentNodeId != 0)
19735
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
19736
0
            node.Depth = parent_settings->Depth + 1;
19737
0
    ctx->DockContext.NodesSettings.push_back(node);
19738
0
}
19739
19740
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
19741
0
{
19742
0
    ImGuiDockNodeSettings node_settings;
19743
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
19744
0
    node_settings.ID = node->ID;
19745
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
19746
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
19747
0
    node_settings.SelectedTabId = node->SelectedTabId;
19748
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
19749
0
    node_settings.Depth = (char)depth;
19750
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
19751
0
    node_settings.Pos = ImVec2ih(node->Pos);
19752
0
    node_settings.Size = ImVec2ih(node->Size);
19753
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
19754
0
    dc->NodesSettings.push_back(node_settings);
19755
0
    if (node->ChildNodes[0])
19756
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
19757
0
    if (node->ChildNodes[1])
19758
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
19759
0
}
19760
19761
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
19762
0
{
19763
0
    ImGuiContext& g = *ctx;
19764
0
    ImGuiDockContext* dc = &ctx->DockContext;
19765
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
19766
0
        return;
19767
19768
    // Gather settings data
19769
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
19770
0
    dc->NodesSettings.resize(0);
19771
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
19772
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
19773
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19774
0
            if (node->IsRootNode())
19775
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
19776
19777
0
    int max_depth = 0;
19778
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19779
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
19780
19781
    // Write to text buffer
19782
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
19783
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19784
0
    {
19785
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
19786
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
19787
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
19788
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
19789
0
        if (node_settings->ParentNodeId)
19790
0
        {
19791
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
19792
0
        }
19793
0
        else
19794
0
        {
19795
0
            if (node_settings->ParentWindowId)
19796
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
19797
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
19798
0
        }
19799
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
19800
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
19801
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
19802
0
            buf->appendf(" NoResize=1");
19803
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
19804
0
            buf->appendf(" CentralNode=1");
19805
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
19806
0
            buf->appendf(" NoTabBar=1");
19807
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
19808
0
            buf->appendf(" HiddenTabBar=1");
19809
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
19810
0
            buf->appendf(" NoWindowMenuButton=1");
19811
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
19812
0
            buf->appendf(" NoCloseButton=1");
19813
0
        if (node_settings->SelectedTabId)
19814
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
19815
19816
        // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
19817
0
        if (g.IO.ConfigDebugIniSettings)
19818
0
            if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
19819
0
            {
19820
0
                buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
19821
0
                if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
19822
0
                    buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
19823
                // Iterate settings so we can give info about windows that didn't exist during the session.
19824
0
                int contains_window = 0;
19825
0
                for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19826
0
                    if (settings->DockId == node_settings->ID)
19827
0
                    {
19828
0
                        if (contains_window++ == 0)
19829
0
                            buf->appendf(" ; contains ");
19830
0
                        buf->appendf("'%s' ", settings->GetName());
19831
0
                    }
19832
0
            }
19833
19834
0
        buf->appendf("\n");
19835
0
    }
19836
0
    buf->appendf("\n");
19837
0
}
19838
19839
19840
//-----------------------------------------------------------------------------
19841
// [SECTION] PLATFORM DEPENDENT HELPERS
19842
//-----------------------------------------------------------------------------
19843
// - Default clipboard handlers
19844
// - Default shell function handlers
19845
// - Default IME handlers
19846
//-----------------------------------------------------------------------------
19847
19848
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
19849
19850
#ifdef _MSC_VER
19851
#pragma comment(lib, "user32")
19852
#pragma comment(lib, "kernel32")
19853
#endif
19854
19855
// Win32 clipboard implementation
19856
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
19857
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19858
{
19859
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19860
    g.ClipboardHandlerData.clear();
19861
    if (!::OpenClipboard(NULL))
19862
        return NULL;
19863
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
19864
    if (wbuf_handle == NULL)
19865
    {
19866
        ::CloseClipboard();
19867
        return NULL;
19868
    }
19869
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
19870
    {
19871
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
19872
        g.ClipboardHandlerData.resize(buf_len);
19873
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
19874
    }
19875
    ::GlobalUnlock(wbuf_handle);
19876
    ::CloseClipboard();
19877
    return g.ClipboardHandlerData.Data;
19878
}
19879
19880
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19881
{
19882
    if (!::OpenClipboard(NULL))
19883
        return;
19884
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
19885
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
19886
    if (wbuf_handle == NULL)
19887
    {
19888
        ::CloseClipboard();
19889
        return;
19890
    }
19891
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
19892
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
19893
    ::GlobalUnlock(wbuf_handle);
19894
    ::EmptyClipboard();
19895
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
19896
        ::GlobalFree(wbuf_handle);
19897
    ::CloseClipboard();
19898
}
19899
19900
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
19901
19902
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
19903
static PasteboardRef main_clipboard = 0;
19904
19905
// OSX clipboard implementation
19906
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
19907
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19908
{
19909
    if (!main_clipboard)
19910
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19911
    PasteboardClear(main_clipboard);
19912
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
19913
    if (cf_data)
19914
    {
19915
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
19916
        CFRelease(cf_data);
19917
    }
19918
}
19919
19920
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19921
{
19922
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19923
    if (!main_clipboard)
19924
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19925
    PasteboardSynchronize(main_clipboard);
19926
19927
    ItemCount item_count = 0;
19928
    PasteboardGetItemCount(main_clipboard, &item_count);
19929
    for (ItemCount i = 0; i < item_count; i++)
19930
    {
19931
        PasteboardItemID item_id = 0;
19932
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
19933
        CFArrayRef flavor_type_array = 0;
19934
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
19935
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
19936
        {
19937
            CFDataRef cf_data;
19938
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
19939
            {
19940
                g.ClipboardHandlerData.clear();
19941
                int length = (int)CFDataGetLength(cf_data);
19942
                g.ClipboardHandlerData.resize(length + 1);
19943
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
19944
                g.ClipboardHandlerData[length] = 0;
19945
                CFRelease(cf_data);
19946
                return g.ClipboardHandlerData.Data;
19947
            }
19948
        }
19949
    }
19950
    return NULL;
19951
}
19952
19953
#else
19954
19955
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
19956
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19957
0
{
19958
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19959
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
19960
0
}
19961
19962
static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
19963
0
{
19964
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19965
0
    g.ClipboardHandlerData.clear();
19966
0
    const char* text_end = text + strlen(text);
19967
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
19968
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
19969
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
19970
0
}
19971
19972
#endif // Default clipboard handlers
19973
19974
//-----------------------------------------------------------------------------
19975
19976
#if defined(__APPLE__) && defined(TARGET_OS_IPHONE) && !defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS)
19977
#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
19978
#endif
19979
19980
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS)
19981
#include <shellapi.h>   // ShellExecuteA()
19982
#ifdef _MSC_VER
19983
#pragma comment(lib, "shell32")
19984
#endif
19985
static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
19986
{
19987
    return (INT_PTR)::ShellExecuteA(NULL, "open", path, NULL, NULL, SW_SHOWDEFAULT) > 32;
19988
}
19989
#elif !defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS)
19990
static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
19991
0
{
19992
#if __APPLE__
19993
    const char* open_executable = "open";
19994
#else
19995
0
    const char* open_executable = "xdg-open";
19996
0
#endif
19997
0
    ImGuiTextBuffer buf;
19998
0
    buf.appendf("%s \"%s\"", open_executable, path);
19999
0
    return system(buf.c_str()) != -1;
20000
0
}
20001
#else
20002
static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { return false; }
20003
#endif // Default shell handlers
20004
20005
//-----------------------------------------------------------------------------
20006
20007
// Win32 API IME support (for Asian languages, etc.)
20008
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
20009
20010
#include <imm.h>
20011
#ifdef _MSC_VER
20012
#pragma comment(lib, "imm32")
20013
#endif
20014
20015
static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data)
20016
{
20017
    // Notify OS Input Method Editor of text input position
20018
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
20019
    if (hwnd == 0)
20020
        return;
20021
20022
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
20023
    if (HIMC himc = ::ImmGetContext(hwnd))
20024
    {
20025
        COMPOSITIONFORM composition_form = {};
20026
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
20027
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
20028
        composition_form.dwStyle = CFS_FORCE_POSITION;
20029
        ::ImmSetCompositionWindow(himc, &composition_form);
20030
        CANDIDATEFORM candidate_form = {};
20031
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
20032
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
20033
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
20034
        ::ImmSetCandidateWindow(himc, &candidate_form);
20035
        ::ImmReleaseContext(hwnd, himc);
20036
    }
20037
}
20038
20039
#else
20040
20041
0
static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData*) {}
20042
20043
#endif // Default IME handlers
20044
20045
//-----------------------------------------------------------------------------
20046
// [SECTION] METRICS/DEBUGGER WINDOW
20047
//-----------------------------------------------------------------------------
20048
// - DebugRenderViewportThumbnail() [Internal]
20049
// - RenderViewportsThumbnails() [Internal]
20050
// - DebugTextEncoding()
20051
// - MetricsHelpMarker() [Internal]
20052
// - ShowFontAtlas() [Internal]
20053
// - ShowMetricsWindow()
20054
// - DebugNodeColumns() [Internal]
20055
// - DebugNodeDockNode() [Internal]
20056
// - DebugNodeDrawList() [Internal]
20057
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
20058
// - DebugNodeFont() [Internal]
20059
// - DebugNodeFontGlyph() [Internal]
20060
// - DebugNodeStorage() [Internal]
20061
// - DebugNodeTabBar() [Internal]
20062
// - DebugNodeViewport() [Internal]
20063
// - DebugNodeWindow() [Internal]
20064
// - DebugNodeWindowSettings() [Internal]
20065
// - DebugNodeWindowsList() [Internal]
20066
// - DebugNodeWindowsListByBeginStackParent() [Internal]
20067
//-----------------------------------------------------------------------------
20068
20069
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
20070
20071
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
20072
0
{
20073
0
    ImGuiContext& g = *GImGui;
20074
0
    ImGuiWindow* window = g.CurrentWindow;
20075
20076
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
20077
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
20078
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
20079
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
20080
0
    for (ImGuiWindow* thumb_window : g.Windows)
20081
0
    {
20082
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
20083
0
            continue;
20084
0
        if (thumb_window->Viewport != viewport)
20085
0
            continue;
20086
20087
0
        ImRect thumb_r = thumb_window->Rect();
20088
0
        ImRect title_r = thumb_window->TitleBarRect();
20089
0
        thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off +  thumb_r.Max * scale));
20090
0
        title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off +  ImVec2(title_r.Max.x, title_r.Min.y + title_r.GetHeight() * 3.0f) * scale)); // Exaggerate title bar height
20091
0
        thumb_r.ClipWithFull(bb);
20092
0
        title_r.ClipWithFull(bb);
20093
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
20094
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
20095
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
20096
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
20097
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
20098
0
    }
20099
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
20100
0
    if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID)
20101
0
        window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
20102
0
}
20103
20104
static void RenderViewportsThumbnails()
20105
0
{
20106
0
    ImGuiContext& g = *GImGui;
20107
0
    ImGuiWindow* window = g.CurrentWindow;
20108
20109
    // Draw monitor and calculate their boundaries
20110
0
    float SCALE = 1.0f / 8.0f;
20111
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
20112
0
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
20113
0
        bb_full.Add(ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize));
20114
0
    ImVec2 p = window->DC.CursorPos;
20115
0
    ImVec2 off = p - bb_full.Min * SCALE;
20116
0
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
20117
0
    {
20118
0
        ImRect monitor_draw_bb(off + (monitor.MainPos) * SCALE, off + (monitor.MainPos + monitor.MainSize) * SCALE);
20119
0
        window->DrawList->AddRect(monitor_draw_bb.Min, monitor_draw_bb.Max, (g.DebugMetricsConfig.HighlightMonitorIdx == g.PlatformIO.Monitors.index_from_ptr(&monitor)) ? IM_COL32(255, 255, 0, 255) : ImGui::GetColorU32(ImGuiCol_Border), 4.0f);
20120
0
        window->DrawList->AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui::GetColorU32(ImGuiCol_Border, 0.10f), 4.0f);
20121
0
    }
20122
20123
    // Draw viewports
20124
0
    for (ImGuiViewportP* viewport : g.Viewports)
20125
0
    {
20126
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
20127
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
20128
0
    }
20129
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
20130
0
}
20131
20132
static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
20133
0
{
20134
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
20135
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
20136
0
    return b->LastFocusedStampCount - a->LastFocusedStampCount;
20137
0
}
20138
20139
// Draw an arbitrary US keyboard layout to visualize translated keys
20140
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
20141
0
{
20142
0
    const float scale = ImGui::GetFontSize() / 13.0f;
20143
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale;
20144
0
    const float  key_rounding = 3.0f * scale;
20145
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale;
20146
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale;
20147
0
    const float  key_face_rounding = 2.0f * scale;
20148
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale;
20149
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
20150
0
    const float  key_row_offset = 9.0f * scale;
20151
20152
0
    ImVec2 board_min = GetCursorScreenPos();
20153
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
20154
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
20155
20156
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
20157
0
    const KeyLayoutData keys_to_display[] =
20158
0
    {
20159
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
20160
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
20161
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
20162
0
    };
20163
20164
    // Elements rendered manually via ImDrawList API are not clipped automatically.
20165
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
20166
0
    Dummy(board_max - board_min);
20167
0
    if (!IsItemVisible())
20168
0
        return;
20169
0
    draw_list->PushClipRect(board_min, board_max, true);
20170
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
20171
0
    {
20172
0
        const KeyLayoutData* key_data = &keys_to_display[n];
20173
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
20174
0
        ImVec2 key_max = key_min + key_size;
20175
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
20176
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
20177
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
20178
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
20179
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
20180
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
20181
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
20182
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
20183
0
        if (IsKeyDown(key_data->Key))
20184
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
20185
0
    }
20186
0
    draw_list->PopClipRect();
20187
0
}
20188
20189
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
20190
void ImGui::DebugTextEncoding(const char* str)
20191
0
{
20192
0
    Text("Text: \"%s\"", str);
20193
0
    if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
20194
0
        return;
20195
0
    TableSetupColumn("Offset");
20196
0
    TableSetupColumn("UTF-8");
20197
0
    TableSetupColumn("Glyph");
20198
0
    TableSetupColumn("Codepoint");
20199
0
    TableHeadersRow();
20200
0
    for (const char* p = str; *p != 0; )
20201
0
    {
20202
0
        unsigned int c;
20203
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
20204
0
        TableNextColumn();
20205
0
        Text("%d", (int)(p - str));
20206
0
        TableNextColumn();
20207
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
20208
0
        {
20209
0
            if (byte_index > 0)
20210
0
                SameLine();
20211
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
20212
0
        }
20213
0
        TableNextColumn();
20214
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
20215
0
            TextUnformatted(p, p + c_utf8_len);
20216
0
        else
20217
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
20218
0
        TableNextColumn();
20219
0
        Text("U+%04X", (int)c);
20220
0
        p += c_utf8_len;
20221
0
    }
20222
0
    EndTable();
20223
0
}
20224
20225
static void DebugFlashStyleColorStop()
20226
0
{
20227
0
    ImGuiContext& g = *GImGui;
20228
0
    if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
20229
0
        g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
20230
0
    g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
20231
0
}
20232
20233
// Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
20234
void ImGui::DebugFlashStyleColor(ImGuiCol idx)
20235
0
{
20236
0
    ImGuiContext& g = *GImGui;
20237
0
    DebugFlashStyleColorStop();
20238
0
    g.DebugFlashStyleColorTime = 0.5f;
20239
0
    g.DebugFlashStyleColorIdx = idx;
20240
0
    g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
20241
0
}
20242
20243
void ImGui::UpdateDebugToolFlashStyleColor()
20244
79.1k
{
20245
79.1k
    ImGuiContext& g = *GImGui;
20246
79.1k
    if (g.DebugFlashStyleColorTime <= 0.0f)
20247
79.1k
        return;
20248
0
    ColorConvertHSVtoRGB(cosf(g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, 0.5f, 0.5f, g.Style.Colors[g.DebugFlashStyleColorIdx].x, g.Style.Colors[g.DebugFlashStyleColorIdx].y, g.Style.Colors[g.DebugFlashStyleColorIdx].z);
20249
0
    g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
20250
0
    if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
20251
0
        DebugFlashStyleColorStop();
20252
0
}
20253
20254
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
20255
static void MetricsHelpMarker(const char* desc)
20256
0
{
20257
0
    ImGui::TextDisabled("(?)");
20258
0
    if (ImGui::BeginItemTooltip())
20259
0
    {
20260
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
20261
0
        ImGui::TextUnformatted(desc);
20262
0
        ImGui::PopTextWrapPos();
20263
0
        ImGui::EndTooltip();
20264
0
    }
20265
0
}
20266
20267
// [DEBUG] List fonts in a font atlas and display its texture
20268
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
20269
0
{
20270
0
    for (ImFont* font : atlas->Fonts)
20271
0
    {
20272
0
        PushID(font);
20273
0
        DebugNodeFont(font);
20274
0
        PopID();
20275
0
    }
20276
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
20277
0
    {
20278
0
        ImGuiContext& g = *GImGui;
20279
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20280
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
20281
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
20282
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
20283
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
20284
0
        TreePop();
20285
0
    }
20286
0
}
20287
20288
void ImGui::ShowMetricsWindow(bool* p_open)
20289
0
{
20290
0
    ImGuiContext& g = *GImGui;
20291
0
    ImGuiIO& io = g.IO;
20292
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20293
0
    if (cfg->ShowDebugLog)
20294
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
20295
0
    if (cfg->ShowIDStackTool)
20296
0
        ShowIDStackToolWindow(&cfg->ShowIDStackTool);
20297
20298
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
20299
0
    {
20300
0
        End();
20301
0
        return;
20302
0
    }
20303
20304
    // [DEBUG] Clear debug breaks hooks after exactly one cycle.
20305
0
    DebugBreakClearData();
20306
20307
    // Basic info
20308
0
    Text("Dear ImGui %s", GetVersion());
20309
0
    if (g.ContextName[0] != 0)
20310
0
    {
20311
0
        SameLine();
20312
0
        Text("(Context Name: \"%s\")", g.ContextName);
20313
0
    }
20314
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
20315
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
20316
0
    Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
20317
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
20318
20319
0
    Separator();
20320
20321
    // Debugging enums
20322
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
20323
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
20324
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
20325
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
20326
0
    if (cfg->ShowWindowsRectsType < 0)
20327
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
20328
0
    if (cfg->ShowTablesRectsType < 0)
20329
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
20330
20331
0
    struct Funcs
20332
0
    {
20333
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
20334
0
        {
20335
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
20336
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
20337
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
20338
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
20339
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
20340
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
20341
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
20342
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
20343
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
20344
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
20345
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); } // Note: y1/y2 not always accurate
20346
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); }
20347
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
20348
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
20349
0
            IM_ASSERT(0);
20350
0
            return ImRect();
20351
0
        }
20352
20353
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
20354
0
        {
20355
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
20356
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
20357
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
20358
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
20359
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
20360
0
            else if (rect_type == WRT_Content)              { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
20361
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
20362
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
20363
0
            IM_ASSERT(0);
20364
0
            return ImRect();
20365
0
        }
20366
0
    };
20367
20368
    // Tools
20369
0
    if (TreeNode("Tools"))
20370
0
    {
20371
        // Debug Break features
20372
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
20373
0
        SeparatorTextEx(0, "Debug breaks", NULL, CalcTextSize("(?)").x + g.Style.SeparatorTextPadding.x);
20374
0
        SameLine();
20375
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
20376
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
20377
0
            DebugStartItemPicker();
20378
0
        Checkbox("Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", &g.IO.ConfigDebugIsDebuggerPresent);
20379
20380
0
        SeparatorText("Visualize");
20381
20382
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
20383
0
        SameLine();
20384
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
20385
20386
0
        Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
20387
0
        SameLine();
20388
0
        MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
20389
20390
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
20391
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
20392
0
        SameLine();
20393
0
        SetNextItemWidth(GetFontSize() * 12);
20394
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
20395
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
20396
0
        {
20397
0
            BulletText("'%s':", g.NavWindow->Name);
20398
0
            Indent();
20399
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
20400
0
            {
20401
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
20402
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
20403
0
            }
20404
0
            Unindent();
20405
0
        }
20406
20407
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
20408
0
        SameLine();
20409
0
        SetNextItemWidth(GetFontSize() * 12);
20410
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
20411
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
20412
0
        {
20413
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20414
0
            {
20415
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20416
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
20417
0
                    continue;
20418
20419
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
20420
0
                if (IsItemHovered())
20421
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20422
0
                Indent();
20423
0
                char buf[128];
20424
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
20425
0
                {
20426
0
                    if (rect_n >= TRT_ColumnsRect)
20427
0
                    {
20428
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
20429
0
                            continue;
20430
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20431
0
                        {
20432
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
20433
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
20434
0
                            Selectable(buf);
20435
0
                            if (IsItemHovered())
20436
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20437
0
                        }
20438
0
                    }
20439
0
                    else
20440
0
                    {
20441
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
20442
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
20443
0
                        Selectable(buf);
20444
0
                        if (IsItemHovered())
20445
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20446
0
                    }
20447
0
                }
20448
0
                Unindent();
20449
0
            }
20450
0
        }
20451
0
        Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
20452
20453
0
        SeparatorText("Validate");
20454
20455
0
        Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
20456
0
        SameLine();
20457
0
        MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
20458
20459
0
        Checkbox("UTF-8 Encoding viewer", &cfg->ShowTextEncodingViewer);
20460
0
        SameLine();
20461
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
20462
0
        if (cfg->ShowTextEncodingViewer)
20463
0
        {
20464
0
            static char buf[64] = "";
20465
0
            SetNextItemWidth(-FLT_MIN);
20466
0
            InputText("##DebugTextEncodingBuf", buf, IM_ARRAYSIZE(buf));
20467
0
            if (buf[0] != 0)
20468
0
                DebugTextEncoding(buf);
20469
0
        }
20470
20471
0
        TreePop();
20472
0
    }
20473
20474
    // Windows
20475
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
20476
0
    {
20477
        //SetNextItemOpen(true, ImGuiCond_Once);
20478
0
        DebugNodeWindowsList(&g.Windows, "By display order");
20479
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
20480
0
        if (TreeNode("By submission order (begin stack)"))
20481
0
        {
20482
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
20483
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
20484
0
            temp_buffer.resize(0);
20485
0
            for (ImGuiWindow* window : g.Windows)
20486
0
                if (window->LastFrameActive + 1 >= g.FrameCount)
20487
0
                    temp_buffer.push_back(window);
20488
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
20489
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
20490
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
20491
0
            TreePop();
20492
0
        }
20493
20494
0
        TreePop();
20495
0
    }
20496
20497
    // DrawLists
20498
0
    int drawlist_count = 0;
20499
0
    for (ImGuiViewportP* viewport : g.Viewports)
20500
0
        drawlist_count += viewport->DrawDataP.CmdLists.Size;
20501
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
20502
0
    {
20503
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
20504
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
20505
0
        for (ImGuiViewportP* viewport : g.Viewports)
20506
0
        {
20507
0
            bool viewport_has_drawlist = false;
20508
0
            for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
20509
0
            {
20510
0
                if (!viewport_has_drawlist)
20511
0
                    Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
20512
0
                viewport_has_drawlist = true;
20513
0
                DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
20514
0
            }
20515
0
        }
20516
0
        TreePop();
20517
0
    }
20518
20519
    // Viewports
20520
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
20521
0
    {
20522
0
        cfg->HighlightMonitorIdx = -1;
20523
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
20524
0
        SameLine();
20525
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
20526
0
        if (open)
20527
0
        {
20528
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
20529
0
            {
20530
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
20531
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
20532
0
                    i, mon.DpiScale * 100.0f,
20533
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
20534
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
20535
0
                if (IsItemHovered())
20536
0
                    cfg->HighlightMonitorIdx = i;
20537
0
            }
20538
0
            TreePop();
20539
0
        }
20540
20541
0
        SetNextItemOpen(true, ImGuiCond_Once);
20542
0
        if (TreeNode("Windows Minimap"))
20543
0
        {
20544
0
            RenderViewportsThumbnails();
20545
0
            TreePop();
20546
0
        }
20547
0
        cfg->HighlightViewportID = 0;
20548
20549
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20550
0
        if (TreeNode("Inferred Z order (front-to-back)"))
20551
0
        {
20552
0
            static ImVector<ImGuiViewportP*> viewports;
20553
0
            viewports.resize(g.Viewports.Size);
20554
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
20555
0
            if (viewports.Size > 1)
20556
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
20557
0
            for (ImGuiViewportP* viewport : viewports)
20558
0
            {
20559
0
                BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
20560
0
                    viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
20561
0
                    (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
20562
0
                    viewport->Window ? viewport->Window->Name : "N/A");
20563
0
                if (IsItemHovered())
20564
0
                    cfg->HighlightViewportID = viewport->ID;
20565
0
            }
20566
0
            TreePop();
20567
0
        }
20568
20569
0
        for (ImGuiViewportP* viewport : g.Viewports)
20570
0
            DebugNodeViewport(viewport);
20571
0
        TreePop();
20572
0
    }
20573
20574
    // Details for Popups
20575
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
20576
0
    {
20577
0
        for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
20578
0
        {
20579
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
20580
0
            ImGuiWindow* window = popup_data.Window;
20581
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'",
20582
0
                popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
20583
0
                popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
20584
0
        }
20585
0
        TreePop();
20586
0
    }
20587
20588
    // Details for TabBars
20589
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
20590
0
    {
20591
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
20592
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
20593
0
            {
20594
0
                PushID(tab_bar);
20595
0
                DebugNodeTabBar(tab_bar, "TabBar");
20596
0
                PopID();
20597
0
            }
20598
0
        TreePop();
20599
0
    }
20600
20601
    // Details for Tables
20602
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
20603
0
    {
20604
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
20605
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
20606
0
                DebugNodeTable(table);
20607
0
        TreePop();
20608
0
    }
20609
20610
    // Details for Fonts
20611
0
    ImFontAtlas* atlas = g.IO.Fonts;
20612
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
20613
0
    {
20614
0
        ShowFontAtlas(atlas);
20615
0
        TreePop();
20616
0
    }
20617
20618
    // Details for InputText
20619
0
    if (TreeNode("InputText"))
20620
0
    {
20621
0
        DebugNodeInputTextState(&g.InputTextState);
20622
0
        TreePop();
20623
0
    }
20624
20625
    // Details for TypingSelect
20626
0
    if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
20627
0
    {
20628
0
        DebugNodeTypingSelectState(&g.TypingSelectState);
20629
0
        TreePop();
20630
0
    }
20631
20632
    // Details for Docking
20633
0
#ifdef IMGUI_HAS_DOCK
20634
0
    if (TreeNode("Docking"))
20635
0
    {
20636
0
        static bool root_nodes_only = true;
20637
0
        ImGuiDockContext* dc = &g.DockContext;
20638
0
        Checkbox("List root nodes", &root_nodes_only);
20639
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
20640
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
20641
0
        SameLine();
20642
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
20643
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
20644
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
20645
0
                if (!root_nodes_only || node->IsRootNode())
20646
0
                    DebugNodeDockNode(node, "Node");
20647
0
        TreePop();
20648
0
    }
20649
0
#endif // #ifdef IMGUI_HAS_DOCK
20650
20651
    // Settings
20652
0
    if (TreeNode("Settings"))
20653
0
    {
20654
0
        if (SmallButton("Clear"))
20655
0
            ClearIniSettings();
20656
0
        SameLine();
20657
0
        if (SmallButton("Save to memory"))
20658
0
            SaveIniSettingsToMemory();
20659
0
        SameLine();
20660
0
        if (SmallButton("Save to disk"))
20661
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
20662
0
        SameLine();
20663
0
        if (g.IO.IniFilename)
20664
0
            Text("\"%s\"", g.IO.IniFilename);
20665
0
        else
20666
0
            TextUnformatted("<NULL>");
20667
0
        Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
20668
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
20669
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
20670
0
        {
20671
0
            for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
20672
0
                BulletText("\"%s\"", handler.TypeName);
20673
0
            TreePop();
20674
0
        }
20675
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
20676
0
        {
20677
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20678
0
                DebugNodeWindowSettings(settings);
20679
0
            TreePop();
20680
0
        }
20681
20682
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
20683
0
        {
20684
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
20685
0
                DebugNodeTableSettings(settings);
20686
0
            TreePop();
20687
0
        }
20688
20689
0
#ifdef IMGUI_HAS_DOCK
20690
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
20691
0
        {
20692
0
            ImGuiDockContext* dc = &g.DockContext;
20693
0
            Text("In SettingsWindows:");
20694
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20695
0
                if (settings->DockId != 0)
20696
0
                    BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
20697
0
            Text("In SettingsNodes:");
20698
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
20699
0
            {
20700
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
20701
0
                const char* selected_tab_name = NULL;
20702
0
                if (settings->SelectedTabId)
20703
0
                {
20704
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
20705
0
                        selected_tab_name = window->Name;
20706
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
20707
0
                        selected_tab_name = window_settings->GetName();
20708
0
                }
20709
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
20710
0
            }
20711
0
            TreePop();
20712
0
        }
20713
0
#endif // #ifdef IMGUI_HAS_DOCK
20714
20715
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
20716
0
        {
20717
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
20718
0
            TreePop();
20719
0
        }
20720
0
        TreePop();
20721
0
    }
20722
20723
    // Settings
20724
0
    if (TreeNode("Memory allocations"))
20725
0
    {
20726
0
        ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
20727
0
        Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
20728
0
        if (SmallButton("GC now")) { g.GcCompactAll = true; }
20729
0
        Text("Recent frames with allocations:");
20730
0
        int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
20731
0
        for (int n = buf_size - 1; n >= 0; n--)
20732
0
        {
20733
0
            ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
20734
0
            BulletText("Frame %06d: %+3d ( %2d malloc, %2d free )%s", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount, (n == 0) ? " (most recent)" : "");
20735
0
        }
20736
0
        TreePop();
20737
0
    }
20738
20739
0
    if (TreeNode("Inputs"))
20740
0
    {
20741
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
20742
0
        {
20743
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
20744
            // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
20745
0
            Indent();
20746
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
20747
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
20748
#else
20749
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key >= 0 && key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
20750
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
20751
#endif
20752
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
20753
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20754
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20755
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
20756
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
20757
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
20758
0
            Unindent();
20759
0
        }
20760
20761
0
        Text("MOUSE STATE");
20762
0
        {
20763
0
            Indent();
20764
0
            if (IsMousePosValid())
20765
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
20766
0
            else
20767
0
                Text("Mouse pos: <INVALID>");
20768
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
20769
0
            int count = IM_ARRAYSIZE(io.MouseDown);
20770
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
20771
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
20772
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
20773
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
20774
0
            Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
20775
0
            Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
20776
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
20777
0
            Unindent();
20778
0
        }
20779
20780
0
        Text("MOUSE WHEELING");
20781
0
        {
20782
0
            Indent();
20783
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
20784
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
20785
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
20786
0
            Unindent();
20787
0
        }
20788
20789
0
        Text("KEY OWNERS");
20790
0
        {
20791
0
            Indent();
20792
0
            if (BeginChild("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20793
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20794
0
                {
20795
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
20796
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
20797
0
                        continue;
20798
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
20799
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
20800
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
20801
0
                }
20802
0
            EndChild();
20803
0
            Unindent();
20804
0
        }
20805
0
        Text("SHORTCUT ROUTING");
20806
0
        SameLine();
20807
0
        MetricsHelpMarker("Declared shortcut routes automatically set key owner when mods matches.");
20808
0
        {
20809
0
            Indent();
20810
0
            if (BeginChild("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20811
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20812
0
                {
20813
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
20814
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
20815
0
                    {
20816
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
20817
0
                        ImGuiKeyChord key_chord = key | routing_data->Mods;
20818
0
                        Text("%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore);
20819
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
20820
0
                        if (g.IO.ConfigDebugIsDebuggerPresent)
20821
0
                        {
20822
0
                            SameLine();
20823
0
                            if (DebugBreakButton("**DebugBreak**", "in SetShortcutRouting() for this KeyChord"))
20824
0
                                g.DebugBreakInShortcutRouting = key_chord;
20825
0
                        }
20826
0
                        idx = routing_data->NextEntryIndex;
20827
0
                    }
20828
0
                }
20829
0
            EndChild();
20830
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20831
0
            Unindent();
20832
0
        }
20833
0
        TreePop();
20834
0
    }
20835
20836
0
    if (TreeNode("Internal state"))
20837
0
    {
20838
0
        Text("WINDOWING");
20839
0
        Indent();
20840
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
20841
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
20842
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
20843
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
20844
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
20845
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20846
0
        Unindent();
20847
20848
0
        Text("ITEMS");
20849
0
        Indent();
20850
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
20851
0
        DebugLocateItemOnHover(g.ActiveId);
20852
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
20853
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20854
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
20855
0
        Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
20856
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
20857
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
20858
0
        Unindent();
20859
20860
0
        Text("NAV,FOCUS");
20861
0
        Indent();
20862
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
20863
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
20864
0
        DebugLocateItemOnHover(g.NavId);
20865
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
20866
0
        Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
20867
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
20868
0
        Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
20869
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
20870
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
20871
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
20872
0
        Text("NavFocusRoute[] = ");
20873
0
        for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
20874
0
        {
20875
0
            const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n];
20876
0
            SameLine(0.0f, 0.0f);
20877
0
            Text("0x%08X/", focus_scope.ID);
20878
0
            SetItemTooltip("In window \"%s\"", FindWindowByID(focus_scope.WindowID)->Name);
20879
0
        }
20880
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
20881
0
        Unindent();
20882
20883
0
        TreePop();
20884
0
    }
20885
20886
    // Overlay: Display windows Rectangles and Begin Order
20887
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
20888
0
    {
20889
0
        for (ImGuiWindow* window : g.Windows)
20890
0
        {
20891
0
            if (!window->WasActive)
20892
0
                continue;
20893
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
20894
0
            if (cfg->ShowWindowsRects)
20895
0
            {
20896
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
20897
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20898
0
            }
20899
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
20900
0
            {
20901
0
                char buf[32];
20902
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
20903
0
                float font_size = GetFontSize();
20904
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
20905
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
20906
0
            }
20907
0
        }
20908
0
    }
20909
20910
    // Overlay: Display Tables Rectangles
20911
0
    if (cfg->ShowTablesRects)
20912
0
    {
20913
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20914
0
        {
20915
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20916
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
20917
0
                continue;
20918
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
20919
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
20920
0
            {
20921
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20922
0
                {
20923
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
20924
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
20925
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
20926
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
20927
0
                }
20928
0
            }
20929
0
            else
20930
0
            {
20931
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
20932
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20933
0
            }
20934
0
        }
20935
0
    }
20936
20937
0
#ifdef IMGUI_HAS_DOCK
20938
    // Overlay: Display Docking info
20939
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
20940
0
    {
20941
0
        char buf[64] = "";
20942
0
        char* p = buf;
20943
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
20944
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
20945
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
20946
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
20947
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
20948
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
20949
0
        int depth = DockNodeGetDepth(node);
20950
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
20951
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
20952
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
20953
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
20954
0
    }
20955
0
#endif // #ifdef IMGUI_HAS_DOCK
20956
20957
0
    End();
20958
0
}
20959
20960
void ImGui::DebugBreakClearData()
20961
0
{
20962
    // Those fields are scattered in their respective subsystem to stay in hot-data locations
20963
0
    ImGuiContext& g = *GImGui;
20964
0
    g.DebugBreakInWindow = 0;
20965
0
    g.DebugBreakInTable = 0;
20966
0
    g.DebugBreakInShortcutRouting = ImGuiKey_None;
20967
0
}
20968
20969
void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location)
20970
0
{
20971
0
    if (!BeginItemTooltip())
20972
0
        return;
20973
0
    Text("To call IM_DEBUG_BREAK() %s:", description_of_location);
20974
0
    Separator();
20975
0
    TextUnformatted(keyboard_only ? "- Press 'Pause/Break' on keyboard." : "- Press 'Pause/Break' on keyboard.\n- or Click (may alter focus/active id).\n- or navigate using keyboard and press space.");
20976
0
    Separator();
20977
0
    TextUnformatted("Choose one way that doesn't interfere with what you are trying to debug!\nYou need a debugger attached or this will crash!");
20978
0
    EndTooltip();
20979
0
}
20980
20981
// Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc.
20982
// In order to reduce interferences with the contents we are trying to debug into.
20983
bool ImGui::DebugBreakButton(const char* label, const char* description_of_location)
20984
0
{
20985
0
    ImGuiWindow* window = GetCurrentWindow();
20986
0
    if (window->SkipItems)
20987
0
        return false;
20988
20989
0
    ImGuiContext& g = *GImGui;
20990
0
    const ImGuiID id = window->GetID(label);
20991
0
    const ImVec2 label_size = CalcTextSize(label, NULL, true);
20992
0
    ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset);
20993
0
    ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y);
20994
20995
0
    const ImRect bb(pos, pos + size);
20996
0
    ItemSize(size, 0.0f);
20997
0
    if (!ItemAdd(bb, id))
20998
0
        return false;
20999
21000
    // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects.
21001
0
    bool hovered = ItemHoverable(bb, id, g.CurrentItemFlags);
21002
0
    bool pressed = hovered && (IsKeyChordPressed(g.DebugBreakKeyChord) || IsMouseClicked(0) || g.NavActivateId == id);
21003
0
    DebugBreakButtonTooltip(false, description_of_location);
21004
21005
0
    ImVec4 col4f = GetStyleColorVec4(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
21006
0
    ImVec4 hsv;
21007
0
    ColorConvertRGBtoHSV(col4f.x, col4f.y, col4f.z, hsv.x, hsv.y, hsv.z);
21008
0
    ColorConvertHSVtoRGB(hsv.x + 0.20f, hsv.y, hsv.z, col4f.x, col4f.y, col4f.z);
21009
21010
0
    RenderNavHighlight(bb, id);
21011
0
    RenderFrame(bb.Min, bb.Max, GetColorU32(col4f), true, g.Style.FrameRounding);
21012
0
    RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, g.Style.ButtonTextAlign, &bb);
21013
21014
0
    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
21015
0
    return pressed;
21016
0
}
21017
21018
// [DEBUG] Display contents of Columns
21019
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
21020
0
{
21021
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
21022
0
        return;
21023
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
21024
0
    for (ImGuiOldColumnData& column : columns->Columns)
21025
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
21026
0
    TreePop();
21027
0
}
21028
21029
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
21030
0
{
21031
0
    using namespace ImGui;
21032
0
    PushID(label);
21033
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
21034
0
    Text("%s:", label);
21035
0
    if (!enabled)
21036
0
        BeginDisabled();
21037
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
21038
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
21039
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
21040
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
21041
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
21042
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
21043
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
21044
0
    CheckboxFlags("DockedWindowsInFocusRoute", p_flags, ImGuiDockNodeFlags_DockedWindowsInFocusRoute);
21045
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags
21046
0
    CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit);
21047
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
21048
0
    CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
21049
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
21050
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
21051
0
    CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking);
21052
0
    if (!enabled)
21053
0
        EndDisabled();
21054
0
    PopStyleVar();
21055
0
    PopID();
21056
0
}
21057
21058
// [DEBUG] Display contents of ImDockNode
21059
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
21060
0
{
21061
0
    ImGuiContext& g = *GImGui;
21062
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
21063
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
21064
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21065
0
    bool open;
21066
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
21067
0
    if (node->Windows.Size > 0)
21068
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
21069
0
    else
21070
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
21071
0
    if (!is_alive) { PopStyleColor(); }
21072
0
    if (is_active && IsItemHovered())
21073
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
21074
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
21075
0
    if (open)
21076
0
    {
21077
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
21078
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
21079
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
21080
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
21081
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
21082
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
21083
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
21084
0
        BulletText("Misc:%s%s%s%s%s%s%s",
21085
0
            node->IsDockSpace() ? " IsDockSpace" : "",
21086
0
            node->IsCentralNode() ? " IsCentralNode" : "",
21087
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
21088
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
21089
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
21090
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
21091
0
        {
21092
0
            if (BeginTable("flags", 4))
21093
0
            {
21094
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
21095
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
21096
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
21097
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
21098
0
                EndTable();
21099
0
            }
21100
0
            TreePop();
21101
0
        }
21102
0
        if (node->ParentNode)
21103
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
21104
0
        if (node->ChildNodes[0])
21105
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
21106
0
        if (node->ChildNodes[1])
21107
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
21108
0
        if (node->TabBar)
21109
0
            DebugNodeTabBar(node->TabBar, "TabBar");
21110
0
        DebugNodeWindowsList(&node->Windows, "Windows");
21111
21112
0
        TreePop();
21113
0
    }
21114
0
}
21115
21116
static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
21117
0
{
21118
0
    union { void* ptr; int integer; } tex_id_opaque;
21119
0
    memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id)));
21120
0
    if (sizeof(tex_id) >= sizeof(void*))
21121
0
        ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr);
21122
0
    else
21123
0
        ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer);
21124
0
}
21125
21126
// [DEBUG] Display contents of ImDrawList
21127
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
21128
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
21129
0
{
21130
0
    ImGuiContext& g = *GImGui;
21131
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
21132
0
    int cmd_count = draw_list->CmdBuffer.Size;
21133
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
21134
0
        cmd_count--;
21135
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
21136
0
    if (draw_list == GetWindowDrawList())
21137
0
    {
21138
0
        SameLine();
21139
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
21140
0
        if (node_open)
21141
0
            TreePop();
21142
0
        return;
21143
0
    }
21144
21145
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
21146
0
    if (window && IsItemHovered() && fg_draw_list)
21147
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
21148
0
    if (!node_open)
21149
0
        return;
21150
21151
0
    if (window && !window->WasActive)
21152
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
21153
21154
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
21155
0
    {
21156
0
        if (pcmd->UserCallback)
21157
0
        {
21158
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
21159
0
            continue;
21160
0
        }
21161
21162
0
        char texid_desc[20];
21163
0
        FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TextureId);
21164
0
        char buf[300];
21165
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
21166
0
            pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
21167
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
21168
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
21169
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
21170
0
        if (!pcmd_node_open)
21171
0
            continue;
21172
21173
        // Calculate approximate coverage area (touched pixel count)
21174
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
21175
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
21176
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
21177
0
        float total_area = 0.0f;
21178
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
21179
0
        {
21180
0
            ImVec2 triangle[3];
21181
0
            for (int n = 0; n < 3; n++, idx_n++)
21182
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
21183
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
21184
0
        }
21185
21186
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
21187
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
21188
0
        Selectable(buf);
21189
0
        if (IsItemHovered() && fg_draw_list)
21190
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
21191
21192
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
21193
0
        ImGuiListClipper clipper;
21194
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
21195
0
        while (clipper.Step())
21196
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
21197
0
            {
21198
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
21199
0
                ImVec2 triangle[3];
21200
0
                for (int n = 0; n < 3; n++, idx_i++)
21201
0
                {
21202
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
21203
0
                    triangle[n] = v.pos;
21204
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
21205
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
21206
0
                }
21207
21208
0
                Selectable(buf, false);
21209
0
                if (fg_draw_list && IsItemHovered())
21210
0
                {
21211
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
21212
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
21213
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
21214
0
                    fg_draw_list->Flags = backup_flags;
21215
0
                }
21216
0
            }
21217
0
        TreePop();
21218
0
    }
21219
0
    TreePop();
21220
0
}
21221
21222
// [DEBUG] Display mesh/aabb of a ImDrawCmd
21223
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
21224
0
{
21225
0
    IM_ASSERT(show_mesh || show_aabb);
21226
21227
    // Draw wire-frame version of all triangles
21228
0
    ImRect clip_rect = draw_cmd->ClipRect;
21229
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
21230
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
21231
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
21232
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
21233
0
    {
21234
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
21235
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
21236
21237
0
        ImVec2 triangle[3];
21238
0
        for (int n = 0; n < 3; n++, idx_n++)
21239
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
21240
0
        if (show_mesh)
21241
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
21242
0
    }
21243
    // Draw bounding boxes
21244
0
    if (show_aabb)
21245
0
    {
21246
0
        out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
21247
0
        out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
21248
0
    }
21249
0
    out_draw_list->Flags = backup_flags;
21250
0
}
21251
21252
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
21253
void ImGui::DebugNodeFont(ImFont* font)
21254
0
{
21255
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
21256
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
21257
0
    SameLine();
21258
0
    if (SmallButton("Set as default"))
21259
0
        GetIO().FontDefault = font;
21260
0
    if (!opened)
21261
0
        return;
21262
21263
    // Display preview text
21264
0
    PushFont(font);
21265
0
    Text("The quick brown fox jumps over the lazy dog");
21266
0
    PopFont();
21267
21268
    // Display details
21269
0
    SetNextItemWidth(GetFontSize() * 8);
21270
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
21271
0
    SameLine(); MetricsHelpMarker(
21272
0
        "Note that the default embedded font is NOT meant to be scaled.\n\n"
21273
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
21274
0
        "You may oversample them to get some flexibility with scaling. "
21275
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
21276
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
21277
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
21278
0
    char c_str[5];
21279
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
21280
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
21281
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
21282
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
21283
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
21284
0
        if (font->ConfigData)
21285
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
21286
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
21287
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
21288
21289
    // Display all glyphs of the fonts in separate pages of 256 characters
21290
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
21291
0
    {
21292
0
        ImDrawList* draw_list = GetWindowDrawList();
21293
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
21294
0
        const float cell_size = font->FontSize * 1;
21295
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
21296
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
21297
0
        {
21298
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
21299
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
21300
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
21301
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
21302
0
            {
21303
0
                base += 4096 - 256;
21304
0
                continue;
21305
0
            }
21306
21307
0
            int count = 0;
21308
0
            for (unsigned int n = 0; n < 256; n++)
21309
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
21310
0
                    count++;
21311
0
            if (count <= 0)
21312
0
                continue;
21313
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
21314
0
                continue;
21315
21316
            // Draw a 16x16 grid of glyphs
21317
0
            ImVec2 base_pos = GetCursorScreenPos();
21318
0
            for (unsigned int n = 0; n < 256; n++)
21319
0
            {
21320
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
21321
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
21322
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
21323
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
21324
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
21325
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
21326
0
                if (!glyph)
21327
0
                    continue;
21328
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
21329
0
                if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
21330
0
                {
21331
0
                    DebugNodeFontGlyph(font, glyph);
21332
0
                    EndTooltip();
21333
0
                }
21334
0
            }
21335
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
21336
0
            TreePop();
21337
0
        }
21338
0
        TreePop();
21339
0
    }
21340
0
    TreePop();
21341
0
}
21342
21343
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
21344
0
{
21345
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
21346
0
    Separator();
21347
0
    Text("Visible: %d", glyph->Visible);
21348
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
21349
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
21350
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
21351
0
}
21352
21353
// [DEBUG] Display contents of ImGuiStorage
21354
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
21355
0
{
21356
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
21357
0
        return;
21358
0
    for (const ImGuiStoragePair& p : storage->Data)
21359
0
    {
21360
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
21361
0
        DebugLocateItemOnHover(p.key);
21362
0
    }
21363
0
    TreePop();
21364
0
}
21365
21366
// [DEBUG] Display contents of ImGuiTabBar
21367
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
21368
0
{
21369
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
21370
0
    char buf[256];
21371
0
    char* p = buf;
21372
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
21373
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
21374
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s  {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
21375
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
21376
0
    {
21377
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
21378
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
21379
0
    }
21380
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
21381
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21382
0
    bool open = TreeNode(label, "%s", buf);
21383
0
    if (!is_active) { PopStyleColor(); }
21384
0
    if (is_active && IsItemHovered())
21385
0
    {
21386
0
        ImDrawList* draw_list = GetForegroundDrawList();
21387
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
21388
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
21389
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
21390
0
    }
21391
0
    if (open)
21392
0
    {
21393
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
21394
0
        {
21395
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
21396
0
            PushID(tab);
21397
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
21398
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
21399
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
21400
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
21401
0
            PopID();
21402
0
        }
21403
0
        TreePop();
21404
0
    }
21405
0
}
21406
21407
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
21408
0
{
21409
0
    ImGuiContext& g = *GImGui;
21410
0
    SetNextItemOpen(true, ImGuiCond_Once);
21411
0
    bool open = TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A");
21412
0
    if (IsItemHovered())
21413
0
        g.DebugMetricsConfig.HighlightViewportID = viewport->ID;
21414
0
    if (open)
21415
0
    {
21416
0
        ImGuiWindowFlags flags = viewport->Flags;
21417
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
21418
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
21419
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
21420
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
21421
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
21422
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
21423
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
21424
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
21425
0
            (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
21426
0
            (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
21427
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
21428
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
21429
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
21430
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
21431
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
21432
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
21433
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
21434
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
21435
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
21436
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
21437
0
        for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
21438
0
            DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
21439
0
        TreePop();
21440
0
    }
21441
0
}
21442
21443
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
21444
0
{
21445
0
    if (window == NULL)
21446
0
    {
21447
0
        BulletText("%s: NULL", label);
21448
0
        return;
21449
0
    }
21450
21451
0
    ImGuiContext& g = *GImGui;
21452
0
    const bool is_active = window->WasActive;
21453
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
21454
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21455
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
21456
0
    if (!is_active) { PopStyleColor(); }
21457
0
    if (IsItemHovered() && is_active)
21458
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
21459
0
    if (!open)
21460
0
        return;
21461
21462
0
    if (window->MemoryCompacted)
21463
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
21464
21465
0
    if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton("**DebugBreak**", "in Begin()"))
21466
0
        g.DebugBreakInWindow = window->ID;
21467
21468
0
    ImGuiWindowFlags flags = window->Flags;
21469
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
21470
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
21471
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
21472
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
21473
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
21474
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
21475
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
21476
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
21477
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
21478
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
21479
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21480
0
    {
21481
0
        ImRect r = window->NavRectRel[layer];
21482
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
21483
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
21484
0
        else
21485
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
21486
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
21487
0
    }
21488
0
    const ImVec2* pr = window->NavPreferredScoringPosRel;
21489
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21490
0
        BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
21491
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
21492
21493
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
21494
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
21495
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
21496
0
    if (window->DockNode || window->DockNodeAsHost)
21497
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
21498
21499
0
    if (window->RootWindow != window)               { DebugNodeWindow(window->RootWindow, "RootWindow"); }
21500
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
21501
0
    if (window->ParentWindow != NULL)               { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
21502
0
    if (window->ParentWindowForFocusRoute != NULL)  { DebugNodeWindow(window->ParentWindowForFocusRoute, "ParentWindowForFocusRoute"); }
21503
0
    if (window->DC.ChildWindows.Size > 0)           { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
21504
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
21505
0
    {
21506
0
        for (ImGuiOldColumns& columns : window->ColumnsStorage)
21507
0
            DebugNodeColumns(&columns);
21508
0
        TreePop();
21509
0
    }
21510
0
    DebugNodeStorage(&window->StateStorage, "Storage");
21511
0
    TreePop();
21512
0
}
21513
21514
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
21515
0
{
21516
0
    if (settings->WantDelete)
21517
0
        BeginDisabled();
21518
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
21519
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
21520
0
    if (settings->WantDelete)
21521
0
        EndDisabled();
21522
0
}
21523
21524
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
21525
0
{
21526
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
21527
0
        return;
21528
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
21529
0
    {
21530
0
        PushID((*windows)[i]);
21531
0
        DebugNodeWindow((*windows)[i], "Window");
21532
0
        PopID();
21533
0
    }
21534
0
    TreePop();
21535
0
}
21536
21537
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
21538
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
21539
0
{
21540
0
    for (int i = 0; i < windows_size; i++)
21541
0
    {
21542
0
        ImGuiWindow* window = windows[i];
21543
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
21544
0
            continue;
21545
0
        char buf[20];
21546
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
21547
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
21548
0
        DebugNodeWindow(window, buf);
21549
0
        Indent();
21550
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
21551
0
        Unindent();
21552
0
    }
21553
0
}
21554
21555
//-----------------------------------------------------------------------------
21556
// [SECTION] DEBUG LOG WINDOW
21557
//-----------------------------------------------------------------------------
21558
21559
void ImGui::DebugLog(const char* fmt, ...)
21560
0
{
21561
0
    va_list args;
21562
0
    va_start(args, fmt);
21563
0
    DebugLogV(fmt, args);
21564
0
    va_end(args);
21565
0
}
21566
21567
void ImGui::DebugLogV(const char* fmt, va_list args)
21568
0
{
21569
0
    ImGuiContext& g = *GImGui;
21570
0
    const int old_size = g.DebugLogBuf.size();
21571
0
    if (g.ContextName[0] != 0)
21572
0
        g.DebugLogBuf.appendf("[%s] [%05d] ", g.ContextName, g.FrameCount);
21573
0
    else
21574
0
        g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
21575
0
    g.DebugLogBuf.appendfv(fmt, args);
21576
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
21577
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
21578
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
21579
#ifdef IMGUI_ENABLE_TEST_ENGINE
21580
    // IMGUI_TEST_ENGINE_LOG() adds a trailing \n automatically
21581
    const int new_size = g.DebugLogBuf.size();
21582
    const bool trailing_carriage_return = (g.DebugLogBuf[new_size - 1] == '\n');
21583
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
21584
        IMGUI_TEST_ENGINE_LOG("%.*s", new_size - old_size - (trailing_carriage_return ? 1 : 0), g.DebugLogBuf.begin() + old_size);
21585
#endif
21586
0
}
21587
21588
// FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout.
21589
static void SameLineOrWrap(const ImVec2& size)
21590
0
{
21591
0
    ImGuiContext& g = *GImGui;
21592
0
    ImGuiWindow* window = g.CurrentWindow;
21593
0
    ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y);
21594
0
    if (window->ClipRect.Contains(ImRect(pos, pos + size)))
21595
0
        ImGui::SameLine();
21596
0
}
21597
21598
static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
21599
0
{
21600
0
    ImGuiContext& g = *GImGui;
21601
0
    ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(name).x, ImGui::GetFrameHeight());
21602
0
    SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
21603
0
    if (ImGui::CheckboxFlags(name, &g.DebugLogFlags, flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
21604
0
    {
21605
0
        g.DebugLogAutoDisableFrames = 2;
21606
0
        g.DebugLogAutoDisableFlags |= flags;
21607
0
    }
21608
0
    ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
21609
0
}
21610
21611
void ImGui::ShowDebugLogWindow(bool* p_open)
21612
0
{
21613
0
    ImGuiContext& g = *GImGui;
21614
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
21615
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
21616
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
21617
0
    {
21618
0
        End();
21619
0
        return;
21620
0
    }
21621
21622
0
    ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting;
21623
0
    CheckboxFlags("All", &g.DebugLogFlags, all_enable_flags);
21624
0
    SetItemTooltip("(except InputRouting which is spammy)");
21625
21626
0
    ShowDebugLogFlag("ActiveId", ImGuiDebugLogFlags_EventActiveId);
21627
0
    ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper);
21628
0
    ShowDebugLogFlag("Docking", ImGuiDebugLogFlags_EventDocking);
21629
0
    ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus);
21630
0
    ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO);
21631
0
    ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav);
21632
0
    ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup);
21633
    //ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection);
21634
0
    ShowDebugLogFlag("Viewport", ImGuiDebugLogFlags_EventViewport);
21635
0
    ShowDebugLogFlag("InputRouting", ImGuiDebugLogFlags_EventInputRouting);
21636
21637
0
    if (SmallButton("Clear"))
21638
0
    {
21639
0
        g.DebugLogBuf.clear();
21640
0
        g.DebugLogIndex.clear();
21641
0
    }
21642
0
    SameLine();
21643
0
    if (SmallButton("Copy"))
21644
0
        SetClipboardText(g.DebugLogBuf.c_str());
21645
0
    SameLine();
21646
0
    if (SmallButton("Configure Outputs.."))
21647
0
        OpenPopup("Outputs");
21648
0
    if (BeginPopup("Outputs"))
21649
0
    {
21650
0
        CheckboxFlags("OutputToTTY", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTTY);
21651
0
#ifndef IMGUI_ENABLE_TEST_ENGINE
21652
0
        BeginDisabled();
21653
0
#endif
21654
0
        CheckboxFlags("OutputToTestEngine", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTestEngine);
21655
0
#ifndef IMGUI_ENABLE_TEST_ENGINE
21656
0
        EndDisabled();
21657
0
#endif
21658
0
        EndPopup();
21659
0
    }
21660
21661
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Border, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
21662
21663
0
    const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
21664
0
    g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
21665
21666
0
    ImGuiListClipper clipper;
21667
0
    clipper.Begin(g.DebugLogIndex.size());
21668
0
    while (clipper.Step())
21669
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
21670
0
            DebugTextUnformattedWithLocateItem(g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no), g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no));
21671
0
    g.DebugLogFlags = backup_log_flags;
21672
0
    if (GetScrollY() >= GetScrollMaxY())
21673
0
        SetScrollHereY(1.0f);
21674
0
    EndChild();
21675
21676
0
    End();
21677
0
}
21678
21679
// Display line, search for 0xXXXXXXXX identifiers and call DebugLocateItemOnHover() when hovered.
21680
void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end)
21681
0
{
21682
0
    TextUnformatted(line_begin, line_end);
21683
0
    if (!IsItemHovered())
21684
0
        return;
21685
0
    ImGuiContext& g = *GImGui;
21686
0
    ImRect text_rect = g.LastItemData.Rect;
21687
0
    for (const char* p = line_begin; p <= line_end - 10; p++)
21688
0
    {
21689
0
        ImGuiID id = 0;
21690
0
        if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
21691
0
            continue;
21692
0
        ImVec2 p0 = CalcTextSize(line_begin, p);
21693
0
        ImVec2 p1 = CalcTextSize(p, p + 10);
21694
0
        g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
21695
0
        if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
21696
0
            DebugLocateItemOnHover(id);
21697
0
        p += 10;
21698
0
    }
21699
0
}
21700
21701
//-----------------------------------------------------------------------------
21702
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
21703
//-----------------------------------------------------------------------------
21704
21705
// Draw a small cross at current CursorPos in current window's DrawList
21706
void ImGui::DebugDrawCursorPos(ImU32 col)
21707
0
{
21708
0
    ImGuiContext& g = *GImGui;
21709
0
    ImGuiWindow* window = g.CurrentWindow;
21710
0
    ImVec2 pos = window->DC.CursorPos;
21711
0
    window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f);
21712
0
    window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f);
21713
0
}
21714
21715
// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
21716
void ImGui::DebugDrawLineExtents(ImU32 col)
21717
0
{
21718
0
    ImGuiContext& g = *GImGui;
21719
0
    ImGuiWindow* window = g.CurrentWindow;
21720
0
    float curr_x = window->DC.CursorPos.x;
21721
0
    float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
21722
0
    float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
21723
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f);
21724
0
    window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f);
21725
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f);
21726
0
}
21727
21728
// Draw last item rect in ForegroundDrawList (so it is always visible)
21729
void ImGui::DebugDrawItemRect(ImU32 col)
21730
0
{
21731
0
    ImGuiContext& g = *GImGui;
21732
0
    ImGuiWindow* window = g.CurrentWindow;
21733
0
    GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
21734
0
}
21735
21736
// [DEBUG] Locate item position/rectangle given an ID.
21737
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
21738
21739
void ImGui::DebugLocateItem(ImGuiID target_id)
21740
0
{
21741
0
    ImGuiContext& g = *GImGui;
21742
0
    g.DebugLocateId = target_id;
21743
0
    g.DebugLocateFrames = 2;
21744
0
    g.DebugBreakInLocateId = false;
21745
0
}
21746
21747
// FIXME: Doesn't work over through a modal window, because they clear HoveredWindow.
21748
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
21749
0
{
21750
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
21751
0
        return;
21752
0
    ImGuiContext& g = *GImGui;
21753
0
    DebugLocateItem(target_id);
21754
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
21755
21756
    // Can't easily use a context menu here because it will mess with focus, active id etc.
21757
0
    if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f)
21758
0
    {
21759
0
        DebugBreakButtonTooltip(false, "in ItemAdd()");
21760
0
        if (IsKeyChordPressed(g.DebugBreakKeyChord))
21761
0
            g.DebugBreakInLocateId = true;
21762
0
    }
21763
0
}
21764
21765
void ImGui::DebugLocateItemResolveWithLastItem()
21766
0
{
21767
0
    ImGuiContext& g = *GImGui;
21768
21769
    // [DEBUG] Debug break requested by user
21770
0
    if (g.DebugBreakInLocateId)
21771
0
        IM_DEBUG_BREAK();
21772
21773
0
    ImGuiLastItemData item_data = g.LastItemData;
21774
0
    g.DebugLocateId = 0;
21775
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
21776
0
    ImRect r = item_data.Rect;
21777
0
    r.Expand(3.0f);
21778
0
    ImVec2 p1 = g.IO.MousePos;
21779
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
21780
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
21781
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
21782
0
}
21783
21784
void ImGui::DebugStartItemPicker()
21785
0
{
21786
0
    ImGuiContext& g = *GImGui;
21787
0
    g.DebugItemPickerActive = true;
21788
0
}
21789
21790
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
21791
void ImGui::UpdateDebugToolItemPicker()
21792
79.1k
{
21793
79.1k
    ImGuiContext& g = *GImGui;
21794
79.1k
    g.DebugItemPickerBreakId = 0;
21795
79.1k
    if (!g.DebugItemPickerActive)
21796
79.1k
        return;
21797
21798
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
21799
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
21800
0
    if (IsKeyPressed(ImGuiKey_Escape))
21801
0
        g.DebugItemPickerActive = false;
21802
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
21803
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
21804
0
    {
21805
0
        g.DebugItemPickerBreakId = hovered_id;
21806
0
        g.DebugItemPickerActive = false;
21807
0
    }
21808
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
21809
0
        if (change_mapping && IsMouseClicked(mouse_button))
21810
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
21811
0
    SetNextWindowBgAlpha(0.70f);
21812
0
    if (!BeginTooltip())
21813
0
        return;
21814
0
    Text("HoveredId: 0x%08X", hovered_id);
21815
0
    Text("Press ESC to abort picking.");
21816
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
21817
0
    if (change_mapping)
21818
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
21819
0
    else
21820
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
21821
0
    EndTooltip();
21822
0
}
21823
21824
// [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
21825
void ImGui::UpdateDebugToolStackQueries()
21826
79.1k
{
21827
79.1k
    ImGuiContext& g = *GImGui;
21828
79.1k
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21829
21830
    // Clear hook when id stack tool is not visible
21831
79.1k
    g.DebugHookIdInfo = 0;
21832
79.1k
    if (g.FrameCount != tool->LastActiveFrame + 1)
21833
79.1k
        return;
21834
21835
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
21836
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
21837
5
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
21838
5
    if (tool->QueryId != query_id)
21839
0
    {
21840
0
        tool->QueryId = query_id;
21841
0
        tool->StackLevel = -1;
21842
0
        tool->Results.resize(0);
21843
0
    }
21844
5
    if (query_id == 0)
21845
5
        return;
21846
21847
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
21848
0
    int stack_level = tool->StackLevel;
21849
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
21850
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
21851
0
            tool->StackLevel++;
21852
21853
    // Update hook
21854
0
    stack_level = tool->StackLevel;
21855
0
    if (stack_level == -1)
21856
0
        g.DebugHookIdInfo = query_id;
21857
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
21858
0
    {
21859
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
21860
0
        tool->Results[stack_level].QueryFrameCount++;
21861
0
    }
21862
0
}
21863
21864
// [DEBUG] ID Stack tool: hooks called by GetID() family functions
21865
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
21866
0
{
21867
0
    ImGuiContext& g = *GImGui;
21868
0
    ImGuiWindow* window = g.CurrentWindow;
21869
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21870
21871
    // Step 0: stack query
21872
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
21873
0
    if (tool->StackLevel == -1)
21874
0
    {
21875
0
        tool->StackLevel++;
21876
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
21877
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
21878
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
21879
0
        return;
21880
0
    }
21881
21882
    // Step 1+: query for individual level
21883
0
    IM_ASSERT(tool->StackLevel >= 0);
21884
0
    if (tool->StackLevel != window->IDStack.Size)
21885
0
        return;
21886
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
21887
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
21888
21889
0
    switch (data_type)
21890
0
    {
21891
0
    case ImGuiDataType_S32:
21892
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
21893
0
        break;
21894
0
    case ImGuiDataType_String:
21895
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
21896
0
        break;
21897
0
    case ImGuiDataType_Pointer:
21898
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
21899
0
        break;
21900
0
    case ImGuiDataType_ID:
21901
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
21902
0
            return;
21903
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
21904
0
        break;
21905
0
    default:
21906
0
        IM_ASSERT(0);
21907
0
    }
21908
0
    info->QuerySuccess = true;
21909
0
    info->DataType = data_type;
21910
0
}
21911
21912
static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
21913
0
{
21914
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
21915
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
21916
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
21917
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
21918
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
21919
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
21920
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
21921
0
        return (*buf = 0);
21922
#ifdef IMGUI_ENABLE_TEST_ENGINE
21923
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
21924
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
21925
#endif
21926
0
    return ImFormatString(buf, buf_size, "???");
21927
0
}
21928
21929
// ID Stack Tool: Display UI
21930
void ImGui::ShowIDStackToolWindow(bool* p_open)
21931
0
{
21932
0
    ImGuiContext& g = *GImGui;
21933
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
21934
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
21935
0
    if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
21936
0
    {
21937
0
        End();
21938
0
        return;
21939
0
    }
21940
21941
    // Display hovered/active status
21942
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21943
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
21944
0
    const ImGuiID active_id = g.ActiveId;
21945
#ifdef IMGUI_ENABLE_TEST_ENGINE
21946
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
21947
#else
21948
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
21949
0
#endif
21950
0
    SameLine();
21951
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
21952
21953
    // CTRL+C to copy path
21954
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
21955
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
21956
0
    SameLine();
21957
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
21958
0
    if (tool->CopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused))
21959
0
    {
21960
0
        tool->CopyToClipboardLastTime = (float)g.Time;
21961
0
        char* p = g.TempBuffer.Data;
21962
0
        char* p_end = p + g.TempBuffer.Size;
21963
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
21964
0
        {
21965
0
            *p++ = '/';
21966
0
            char level_desc[256];
21967
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
21968
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
21969
0
            {
21970
0
                if (level_desc[n] == '/')
21971
0
                    *p++ = '\\';
21972
0
                *p++ = level_desc[n];
21973
0
            }
21974
0
        }
21975
0
        *p = '\0';
21976
0
        SetClipboardText(g.TempBuffer.Data);
21977
0
    }
21978
21979
    // Display decorated stack
21980
0
    tool->LastActiveFrame = g.FrameCount;
21981
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
21982
0
    {
21983
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
21984
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
21985
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
21986
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
21987
0
        TableHeadersRow();
21988
0
        for (int n = 0; n < tool->Results.Size; n++)
21989
0
        {
21990
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
21991
0
            TableNextColumn();
21992
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
21993
0
            TableNextColumn();
21994
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
21995
0
            TextUnformatted(g.TempBuffer.Data);
21996
0
            TableNextColumn();
21997
0
            Text("0x%08X", info->ID);
21998
0
            if (n == tool->Results.Size - 1)
21999
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
22000
0
        }
22001
0
        EndTable();
22002
0
    }
22003
0
    End();
22004
0
}
22005
22006
#else
22007
22008
void ImGui::ShowMetricsWindow(bool*) {}
22009
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
22010
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
22011
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
22012
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
22013
void ImGui::DebugNodeFont(ImFont*) {}
22014
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
22015
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
22016
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
22017
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
22018
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
22019
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
22020
22021
void ImGui::ShowDebugLogWindow(bool*) {}
22022
void ImGui::ShowIDStackToolWindow(bool*) {}
22023
void ImGui::DebugStartItemPicker() {}
22024
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
22025
22026
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
22027
22028
//-----------------------------------------------------------------------------
22029
22030
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
22031
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
22032
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
22033
#include "imgui_user.inl"
22034
#endif
22035
22036
//-----------------------------------------------------------------------------
22037
22038
#endif // #ifndef IMGUI_DISABLE